diff --git a/.gitignore b/.gitignore index 82484b8..f3f19ce 100644 --- a/.gitignore +++ b/.gitignore @@ -38,7 +38,7 @@ build* subprojects/* !/subprojects/*.wrap !/subprojects/doctest -!/subprojects/fstlib +!/subprojects/packagefiles # Meson log files */meson-info/* diff --git a/CHANGELOG.md b/CHANGELOG.md index 18bb339..0d71c00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # COATi Release Notes and Changelog +## Unreleased + +### Notes for Developers + - OpenFst is no longer bundled. An installed OpenFst (1.8.4 or later) is + used when a test program links against it; otherwise Meson downloads and + builds OpenFst 1.8.5 (`subprojects/openfst.wrap`). + `-Dsystem_openfst=disabled` always uses the download, + `-Dsystem_openfst=enabled` requires the installed one. + ## v1.0 (May 2023) ### Features diff --git a/README.md b/README.md index eaf86af..3fab9bf 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,9 @@ Source code for the most recent beta versions is available at -Michael Riley - -Contributors: - -These contributions range from fundamental algorithmic contributions (e.g., -Mehryar Mohri) to implementation of core components and extensions. - -Tom Bagby -Dan Bikel -Kyle Gorman -Martin Jansche -Boulos Harb -Mehryar Mohri -Dan Povey -Kasturi Raghavan -Jacob Ratkiewicz -Jesse Rosenstock -Johan Schalkwyk -Masha Shugrina -Wojtek Skut -Jeffrey Sorensen -Richard Sproat -Ananda Theertha Suresh -Terry Tai -Lawrence Wolf-Sonkin -Ke Wu diff --git a/contrib/fstlib/COPYING b/contrib/fstlib/COPYING deleted file mode 100644 index d88414a..0000000 --- a/contrib/fstlib/COPYING +++ /dev/null @@ -1,13 +0,0 @@ -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use these files 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. - -Copyright 2005-2020 Google LLC. diff --git a/contrib/fstlib/compat.cc b/contrib/fstlib/compat.cc deleted file mode 100644 index b403f5a..0000000 --- a/contrib/fstlib/compat.cc +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// Google compatibility definitions. - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -CheckSummer::CheckSummer() : count_(0) { - check_sum_.resize(kCheckSumLength, '\0'); -} - -void CheckSummer::Reset() { - count_ = 0; - for (int i = 0; i < kCheckSumLength; ++i) check_sum_[i] = '\0'; -} - -void CheckSummer::Update(std::string_view data) { - for (int i = 0; i < data.size(); ++i) { - check_sum_[(count_++) % kCheckSumLength] ^= data[i]; - } -} - -namespace internal { - -std::vector StringSplitter::SplitToSv() { - std::vector vec; - if (delim_.empty()) { - if (string_.empty() && !skip_empty_) { - vec.push_back(""); - } else { - // If empty delimiter, then simply return every character separately as a - // single-character string_view. - vec.reserve(string_.size()); - for (int i = 0; i < string_.size(); ++i) { - vec.push_back(string_.substr(i, 1)); - } - } - return vec; - } - size_t prev_pos = 0, pos = 0; - while (pos <= string_.length()) { - pos = string_.find_first_of(delim_, pos); - if (pos == std::string_view::npos) { - pos = string_.length(); - } - if (!skip_empty_ || pos != prev_pos) { - vec.push_back(string_.substr(prev_pos, pos - prev_pos)); - } - prev_pos = ++pos; - } - return vec; -} - -} // namespace internal - -internal::StringSplitter StrSplit(std::string_view full, ByAnyChar delim) { - return internal::StringSplitter(full, std::move(delim).delimiters); -} - -internal::StringSplitter StrSplit(std::string_view full, char delim) { - return StrSplit(full, ByAnyChar(std::string_view(&delim, 1))); -} - -internal::StringSplitter StrSplit(std::string_view full, ByAnyChar delim, - SkipEmpty) { - return internal::StringSplitter(full, std::move(delim).delimiters, - /*skip_empty=*/true); -} - -internal::StringSplitter StrSplit(std::string_view full, char delim, - SkipEmpty) { - return StrSplit(full, ByAnyChar(std::string_view(&delim, 1)), SkipEmpty()); -} - -namespace { -bool IsAsciiSpace(unsigned char ch) { return std::isspace(ch); } -} // namespace - -std::string_view StripTrailingAsciiWhitespace(std::string_view full) { - auto it = std::find_if_not(full.rbegin(), full.rend(), IsAsciiSpace); - return full.substr(0, full.rend() - it); -} - -void StripTrailingAsciiWhitespace(std::string *full) { - auto it = std::find_if_not(full->rbegin(), full->rend(), IsAsciiSpace); - full->erase(full->rend() - it); -} - -} // namespace fst diff --git a/contrib/fstlib/encode.cc b/contrib/fstlib/encode.cc deleted file mode 100644 index 57ccaaf..0000000 --- a/contrib/fstlib/encode.cc +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Definitions for encode table header. - -#include - -#include -#include -#include -#include -#include - -#include -#include - -namespace fst { - -bool EncodeTableHeader::Read(std::istream &strm, std::string_view source) { - int32_t magic_number; - ReadType(strm, &magic_number); - switch (magic_number) { - case internal::kEncodeMagicNumber: { - ReadType(strm, &arctype_); - ReadType(strm, &flags_); - ReadType(strm, &size_); - break; - } - case internal::kEncodeDeprecatedMagicNumber: { - LOG(ERROR) << "This old-style Encoder is written in a deprecated " - "format and will soon cease to be readable. Please read " - "and re-write it in order to be future-proof."; - // TODO(b/141172858): deprecated, remove by 2020-01-01. - uint32_t flags; - ReadType(strm, &flags); - flags_ = flags; - int64_t size; - ReadType(strm, &size); - size_ = size; - break; - } - default: { - LOG(ERROR) << "EncodeTableHeader::Read: Bad encode table header: " - << source; - return false; - } - } - if (!strm) { - LOG(ERROR) << "EncodeTableHeader::Read: Read failed: " << source; - return false; - } - return true; -} - -bool EncodeTableHeader::Write(std::ostream &strm, - std::string_view source) const { - WriteType(strm, internal::kEncodeMagicNumber); - WriteType(strm, arctype_); - WriteType(strm, flags_); - WriteType(strm, size_); - strm.flush(); - if (!strm) { - LOG(ERROR) << "EncodeTableHeader::Write: Write failed: " << source; - return false; - } - return true; -} - -} // namespace fst diff --git a/contrib/fstlib/flags.cc b/contrib/fstlib/flags.cc deleted file mode 100644 index b32460d..0000000 --- a/contrib/fstlib/flags.cc +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// Google-style flag handling definitions. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -static const char *private_tmpdir = getenv("TMPDIR"); - -DEFINE_int32(v, 0, "verbosity level"); -DEFINE_bool(help, false, "show usage information"); -DEFINE_bool(helpshort, false, "show brief usage information"); -DEFINE_string(tmpdir, private_tmpdir ? private_tmpdir : "/tmp", - "temporary directory"); - -static std::string flag_usage; -static std::string prog_src; - -// Sets prog_src to src. -static void SetProgSrc(const char *src) { - prog_src = src; - // Remove "-main" in src filename. Flags are defined in fstx.cc but SetFlags() - // is called in fstx-main.cc, which results in a filename mismatch in - // ShowUsageRestrict() below. - static constexpr std::string_view kMainSuffix = "-main.cc"; - const int prefix_length = prog_src.size() - kMainSuffix.size(); - if (prefix_length > 0 && - std::string_view(prog_src).substr(prefix_length) == kMainSuffix) { - static constexpr size_t kDashMainSize = std::string_view("-main").size(); - prog_src.erase(prefix_length, kDashMainSize); - } -} - -void SetFlags(const char *usage, int *argc, char ***argv, - bool remove_flags, const char *src) { - flag_usage = usage; - SetProgSrc(src); - - int index = 1; - for (; index < *argc; ++index) { - std::string_view argval = (*argv)[index]; - if (argval[0] != '-' || argval == "-") break; - while (argval[0] == '-') argval.remove_prefix(1); // Removes initial '-'. - std::string arg(argval); - std::string val(""); - // Splits argval (arg=val) into arg and val. - auto pos = argval.find('='); - if (pos != std::string::npos) { - arg = argval.substr(0, pos); - val = argval.substr(pos + 1); - } - auto bool_register = FlagRegister::GetRegister(); - if (bool_register->SetFlag(arg, val)) - continue; - auto string_register = FlagRegister::GetRegister(); - if (string_register->SetFlag(arg, val)) continue; - auto int32_register = FlagRegister::GetRegister(); - if (int32_register->SetFlag(arg, val)) continue; - auto int64_register = FlagRegister::GetRegister(); - if (int64_register->SetFlag(arg, val)) continue; - auto uint64_register = FlagRegister::GetRegister(); - if (uint64_register->SetFlag(arg, val)) continue; - auto double_register = FlagRegister::GetRegister(); - if (double_register->SetFlag(arg, val)) continue; - LOG(FATAL) << "SetFlags: Bad option: " << (*argv)[index]; - } - if (remove_flags) { - for (auto i = 0; i < *argc - index; ++i) { - (*argv)[i + 1] = (*argv)[i + index]; - } - *argc -= index - 1; - } - if (FST_FLAGS_help) { - ShowUsage(true); - exit(1); - } - if (FST_FLAGS_helpshort) { - ShowUsage(false); - exit(1); - } -} - -// If flag is defined in file 'src' and 'in_src' true or is not -// defined in file 'src' and 'in_src' is false, then print usage. -static void ShowUsageRestrict( - const std::set> &usage_set, - const std::string &src, bool in_src, bool show_file) { - std::string old_file; - bool file_out = false; - bool usage_out = false; - for (const auto &pair : usage_set) { - const auto &file = pair.first; - const auto &usage = pair.second; - bool match = file == src; - if ((match && !in_src) || (!match && in_src)) continue; - if (file != old_file) { - if (show_file) { - if (file_out) std::cout << std::endl; - std::cout << "Flags from: " << file << std::endl; - file_out = true; - } - old_file = file; - } - std::cout << usage << std::endl; - usage_out = true; - } - if (usage_out) std::cout << std::endl; -} - -void FailedNewHandler() { - std::cerr << "Memory allocation failed" << std::endl; - std::exit(1); -} - -void ShowUsage(bool long_usage) { - std::set> usage_set; - std::cout << flag_usage << std::endl; - auto bool_register = FlagRegister::GetRegister(); - bool_register->GetUsage(&usage_set); - auto string_register = FlagRegister::GetRegister(); - string_register->GetUsage(&usage_set); - auto int32_register = FlagRegister::GetRegister(); - int32_register->GetUsage(&usage_set); - auto int64_register = FlagRegister::GetRegister(); - int64_register->GetUsage(&usage_set); - auto uint64_register = FlagRegister::GetRegister(); - uint64_register->GetUsage(&usage_set); - auto double_register = FlagRegister::GetRegister(); - double_register->GetUsage(&usage_set); - if (!prog_src.empty()) { - std::cout << "PROGRAM FLAGS:" << std::endl << std::endl; - ShowUsageRestrict(usage_set, prog_src, true, false); - } - if (!long_usage) return; - if (!prog_src.empty()) { - std::cout << "LIBRARY FLAGS:" << std::endl << std::endl; - } - ShowUsageRestrict(usage_set, prog_src, false, true); -} diff --git a/contrib/fstlib/fst-types.cc b/contrib/fstlib/fst-types.cc deleted file mode 100644 index dd4e164..0000000 --- a/contrib/fstlib/fst-types.cc +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Registration of common FST and arc types. - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -REGISTER_FST(VectorFst, StdArc); -REGISTER_FST(VectorFst, LogArc); -REGISTER_FST(VectorFst, Log64Arc); - -REGISTER_FST(ConstFst, StdArc); -REGISTER_FST(ConstFst, LogArc); -REGISTER_FST(ConstFst, Log64Arc); - -REGISTER_FST(EditFst, StdArc); -REGISTER_FST(EditFst, LogArc); -REGISTER_FST(EditFst, Log64Arc); - -REGISTER_FST(CompactStringFst, StdArc); -REGISTER_FST(CompactStringFst, LogArc); -REGISTER_FST(CompactStringFst, Log64Arc); - -REGISTER_FST(CompactWeightedStringFst, StdArc); -REGISTER_FST(CompactWeightedStringFst, LogArc); -REGISTER_FST(CompactWeightedStringFst, Log64Arc); - -REGISTER_FST(CompactAcceptorFst, StdArc); -REGISTER_FST(CompactAcceptorFst, LogArc); -REGISTER_FST(CompactAcceptorFst, Log64Arc); - -REGISTER_FST(CompactUnweightedFst, StdArc); -REGISTER_FST(CompactUnweightedFst, LogArc); -REGISTER_FST(CompactUnweightedFst, Log64Arc); - -REGISTER_FST(CompactUnweightedAcceptorFst, StdArc); -REGISTER_FST(CompactUnweightedAcceptorFst, LogArc); -REGISTER_FST(CompactUnweightedAcceptorFst, Log64Arc); - -} // namespace fst diff --git a/contrib/fstlib/fst.cc b/contrib/fstlib/fst.cc deleted file mode 100644 index 7532034..0000000 --- a/contrib/fstlib/fst.cc +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST definitions. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -// FST flag definitions. - -DEFINE_bool(fst_verify_properties, false, - "Verify FST properties queried by TestProperties"); - -DEFINE_bool(fst_default_cache_gc, true, "Enable garbage collection of cache"); - -DEFINE_int64(fst_default_cache_gc_limit, 1 << 20LL, - "Cache byte size that triggers garbage collection"); - -DEFINE_bool(fst_align, false, "Write FST data aligned where appropriate"); - -DEFINE_string(save_relabel_ipairs, "", "Save input relabel pairs to file"); -DEFINE_string(save_relabel_opairs, "", "Save output relabel pairs to file"); - -DEFINE_string(fst_read_mode, "read", - "Default file reading mode for mappable files"); - -namespace fst { - -// Checks FST magic number and reads in the header; if rewind = true, -// the stream is repositioned before call if possible. -bool FstHeader::Read(std::istream &strm, const std::string &source, - bool rewind) { - int64_t pos = 0; - if (rewind) pos = strm.tellg(); - int32_t magic_number = 0; - ReadType(strm, &magic_number); - if (magic_number != kFstMagicNumber) { - LOG(ERROR) << "FstHeader::Read: Bad FST header: " << source - << ". Magic number not matched. Got: " << magic_number; - if (rewind) strm.seekg(pos); - return false; - } - ReadType(strm, &fsttype_); - ReadType(strm, &arctype_); - ReadType(strm, &version_); - ReadType(strm, &flags_); - ReadType(strm, &properties_); - ReadType(strm, &start_); - ReadType(strm, &numstates_); - ReadType(strm, &numarcs_); - if (!strm) { - LOG(ERROR) << "FstHeader::Read: Read failed: " << source; - return false; - } - if (rewind) strm.seekg(pos); - return true; -} - -// Writes FST magic number and FST header. -bool FstHeader::Write(std::ostream &strm, std::string_view) const { - WriteType(strm, kFstMagicNumber); - WriteType(strm, fsttype_); - WriteType(strm, arctype_); - WriteType(strm, version_); - WriteType(strm, flags_); - WriteType(strm, properties_); - WriteType(strm, start_); - WriteType(strm, numstates_); - WriteType(strm, numarcs_); - return true; -} - -std::string FstHeader::DebugString() const { - std::ostringstream ostrm; - ostrm << "fsttype: \"" << fsttype_ << "\" arctype: \"" << arctype_ - << "\" version: \"" << version_ << "\" flags: \"" << flags_ - << "\" properties: \"" << properties_ << "\" start: \"" << start_ - << "\" numstates: \"" << numstates_ << "\" numarcs: \"" << numarcs_ - << "\""; - return ostrm.str(); -} - -FstReadOptions::FstReadOptions(const std::string_view source, - const FstHeader * header, - const SymbolTable * isymbols, - const SymbolTable * osymbols) - : source(source), - header(header), - isymbols(isymbols), - osymbols(osymbols), - read_isymbols(true), - read_osymbols(true) { - mode = ReadMode(FST_FLAGS_fst_read_mode); -} - -FstReadOptions::FstReadOptions(const std::string_view source, - const SymbolTable *isymbols, - const SymbolTable *osymbols) - : FstReadOptions(source, /*header=*/nullptr, isymbols, osymbols) {} - -FstReadOptions::FileReadMode FstReadOptions::ReadMode(std::string_view mode) { - if (mode == "read") return READ; - if (mode == "map") return MAP; - LOG(ERROR) << "Unknown file read mode " << mode; - return READ; -} - -std::string FstReadOptions::DebugString() const { - std::ostringstream ostrm; - ostrm << "source: \"" << source << "\" mode: \"" - << (mode == READ ? "READ" : "MAP") << "\" read_isymbols: \"" - << (read_isymbols ? "true" : "false") << "\" read_osymbols: \"" - << (read_osymbols ? "true" : "false") << "\" header: \"" - << (header ? "set" : "null") << "\" isymbols: \"" - << (isymbols ? "set" : "null") << "\" osymbols: \"" - << (osymbols ? "set" : "null") << "\""; - return ostrm.str(); -} - -} // namespace fst diff --git a/contrib/fstlib/fst/accumulator.h b/contrib/fstlib/fst/accumulator.h deleted file mode 100644 index b6e063e..0000000 --- a/contrib/fstlib/fst/accumulator.h +++ /dev/null @@ -1,928 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes to accumulate arc weights. Useful for weight lookahead. - -#ifndef FST_ACCUMULATOR_H_ -#define FST_ACCUMULATOR_H_ - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// This class accumulates arc weights using the semiring Plus(). -// Sum(w, aiter, begin, end) has time complexity O(begin - end). -template -class DefaultAccumulator { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - DefaultAccumulator() = default; - - DefaultAccumulator(const DefaultAccumulator &acc, bool safe = false) {} - - void Init(const Fst &fst, bool copy = false) {} - - void SetState(StateId state) {} - - Weight Sum(Weight w, Weight v) { return Plus(w, v); } - - template - Weight Sum(Weight w, ArcIter *aiter, ssize_t begin, ssize_t end) { - Adder adder(w); // maintains cumulative sum accurately - aiter->Seek(begin); - for (auto pos = begin; pos < end; aiter->Next(), ++pos) - adder.Add(aiter->Value().weight); - return adder.Sum(); - } - - constexpr bool Error() const { return false; } - - private: - DefaultAccumulator &operator=(const DefaultAccumulator &) = delete; -}; - -// This class accumulates arc weights using the log semiring Plus() assuming an -// arc weight has a WeightConvert specialization to and from log64 weights. -// Sum(w, aiter, begin, end) has time complexity O(begin - end). -template -class LogAccumulator { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - LogAccumulator() = default; - - LogAccumulator(const LogAccumulator &acc, bool safe = false) {} - - void Init(const Fst &fst, bool copy = false) {} - - void SetState(StateId s) {} - - Weight Sum(Weight w, Weight v) { return LogPlus(w, v); } - - template - Weight Sum(Weight w, ArcIter *aiter, ssize_t begin, ssize_t end) { - auto sum = w; - aiter->Seek(begin); - for (auto pos = begin; pos < end; aiter->Next(), ++pos) { - sum = LogPlus(sum, aiter->Value().weight); - } - return sum; - } - - constexpr bool Error() const { return false; } - - private: - Weight LogPlus(Weight w, Weight v) { - if (w == Weight::Zero()) { - return v; - } - const auto f1 = to_log_weight_(w).Value(); - const auto f2 = to_log_weight_(v).Value(); - if (f1 > f2) { - return to_weight_(Log64Weight(f2 - internal::LogPosExp(f1 - f2))); - } else { - return to_weight_(Log64Weight(f1 - internal::LogPosExp(f2 - f1))); - } - } - - const WeightConvert to_log_weight_{}; - const WeightConvert to_weight_{}; - - LogAccumulator &operator=(const LogAccumulator &) = delete; -}; - -// Interface for shareable data for fast log accumulator copies. Holds pointers -// to data only, storage is provided by derived classes. -class FastLogAccumulatorData { - public: - FastLogAccumulatorData(int arc_limit, int arc_period) - : arc_limit_(arc_limit), - arc_period_(arc_period), - weights_ptr_(nullptr), - num_weights_(0), - weight_positions_ptr_(nullptr), - num_positions_(0) {} - - virtual ~FastLogAccumulatorData() = default; - - // Cummulative weight per state for all states s.t. # of arcs > arc_limit_ - // with arcs in order. The first element per state is Log64Weight::Zero(). - const double *Weights() const { return weights_ptr_; } - - int NumWeights() const { return num_weights_; } - - // Maps from state to corresponding beginning weight position in weights_. - // osition -1 means no pre-computed weights for that state. - const int *WeightPositions() const { return weight_positions_ptr_; } - - int NumPositions() const { return num_positions_; } - - int ArcLimit() const { return arc_limit_; } - - int ArcPeriod() const { return arc_period_; } - - // Returns true if the data object is mutable and supports SetData(). - virtual bool IsMutable() const = 0; - - // Does not take ownership but may invalidate the contents of weights and - // weight_positions. - virtual void SetData(std::vector *weights, - std::vector *weight_positions) = 0; - - protected: - void Init(int num_weights, const double *weights, int num_positions, - const int *weight_positions) { - weights_ptr_ = weights; - num_weights_ = num_weights; - weight_positions_ptr_ = weight_positions; - num_positions_ = num_positions; - } - - private: - const int arc_limit_; - const int arc_period_; - const double *weights_ptr_; - int num_weights_; - const int *weight_positions_ptr_; - int num_positions_; - - FastLogAccumulatorData(const FastLogAccumulatorData &) = delete; - FastLogAccumulatorData &operator=(const FastLogAccumulatorData &) = delete; -}; - -// FastLogAccumulatorData with mutable storage; filled by -// FastLogAccumulator::Init. -class MutableFastLogAccumulatorData : public FastLogAccumulatorData { - public: - MutableFastLogAccumulatorData(int arc_limit, int arc_period) - : FastLogAccumulatorData(arc_limit, arc_period) {} - - bool IsMutable() const override { return true; } - - void SetData(std::vector *weights, - std::vector *weight_positions) override { - weights_.swap(*weights); - weight_positions_.swap(*weight_positions); - Init(weights_.size(), weights_.data(), weight_positions_.size(), - weight_positions_.data()); - } - - private: - std::vector weights_; - std::vector weight_positions_; - - MutableFastLogAccumulatorData(const MutableFastLogAccumulatorData &) = delete; - MutableFastLogAccumulatorData &operator=( - const MutableFastLogAccumulatorData &) = delete; -}; - -// This class accumulates arc weights using the log semiring Plus() assuming an -// arc weight has a WeightConvert specialization to and from log64 weights. The -// member function Init(fst) has to be called to setup pre-computed weight -// information. -// Sum(w, aiter, begin, end) has time complexity O(arc_limit_) or O(arc_period_) -// depending on whether the state has more than arc_limit_ arcs -// Space complexity is O(CountStates(fst) + CountArcs(fst) / arc_period_). -template -class FastLogAccumulator { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit FastLogAccumulator(ssize_t arc_limit = 20, ssize_t arc_period = 10) - : to_log_weight_(), - to_weight_(), - arc_limit_(arc_limit), - arc_period_(arc_period), - data_(std::make_shared(arc_limit, - arc_period)), - state_weights_(nullptr), - error_(false) {} - - explicit FastLogAccumulator(std::shared_ptr data) - : to_log_weight_(), - to_weight_(), - arc_limit_(data->ArcLimit()), - arc_period_(data->ArcPeriod()), - data_(data), - state_weights_(nullptr), - error_(false) {} - - FastLogAccumulator(const FastLogAccumulator &acc, bool safe = false) - : to_log_weight_(), - to_weight_(), - arc_limit_(acc.arc_limit_), - arc_period_(acc.arc_period_), - data_(acc.data_), - state_weights_(nullptr), - error_(acc.error_) {} - - void SetState(StateId s) { - const auto *weights = data_->Weights(); - const auto *weight_positions = data_->WeightPositions(); - state_weights_ = nullptr; - if (s < data_->NumPositions()) { - const auto pos = weight_positions[s]; - if (pos >= 0) state_weights_ = &(weights[pos]); - } - } - - Weight Sum(Weight w, Weight v) const { return LogPlus(w, v); } - - template - Weight Sum(Weight w, ArcIter *aiter, ssize_t begin, ssize_t end) const { - if (error_) return Weight::NoWeight(); - auto sum = w; - // Finds begin and end of pre-stored weights. - ssize_t index_begin = -1; - ssize_t index_end = -1; - ssize_t stored_begin = end; - ssize_t stored_end = end; - if (state_weights_) { - index_begin = begin > 0 ? (begin - 1) / arc_period_ + 1 : 0; - index_end = end / arc_period_; - stored_begin = index_begin * arc_period_; - stored_end = index_end * arc_period_; - } - // Computes sum before pre-stored weights. - if (begin < stored_begin) { - const auto pos_end = std::min(stored_begin, end); - aiter->Seek(begin); - for (auto pos = begin; pos < pos_end; aiter->Next(), ++pos) { - sum = LogPlus(sum, aiter->Value().weight); - } - } - // Computes sum between pre-stored weights. - if (stored_begin < stored_end) { - const auto f1 = state_weights_[index_end]; - const auto f2 = state_weights_[index_begin]; - if (f1 < f2) sum = LogPlus(sum, LogMinus(f1, f2)); - // Commented out for efficiency; adds Zero(). - /* - else { - // explicitly computes if cumulative sum lacks precision - aiter->Seek(stored_begin); - for (auto pos = stored_begin; pos < stored_end; aiter->Next(), ++pos) - sum = LogPlus(sum, aiter->Value().weight); - } - */ - } - // Computes sum after pre-stored weights. - if (stored_end < end) { - const auto pos_start = std::max(stored_begin, stored_end); - aiter->Seek(pos_start); - for (auto pos = pos_start; pos < end; aiter->Next(), ++pos) { - sum = LogPlus(sum, aiter->Value().weight); - } - } - return sum; - } - - template - void Init(const FST &fst, bool copy = false) { - if (copy || !data_->IsMutable()) return; - if (data_->NumPositions() != 0 || arc_limit_ < arc_period_) { - FSTERROR() << "FastLogAccumulator: Initialization error"; - error_ = true; - return; - } - std::vector weights; - std::vector weight_positions; - weight_positions.reserve(CountStates(fst)); - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - if (fst.NumArcs(s) >= arc_limit_) { - auto sum = FloatLimits::PosInfinity(); - if (weight_positions.size() <= s) weight_positions.resize(s + 1, -1); - weight_positions[s] = weights.size(); - weights.push_back(sum); - size_t narcs = 0; - ArcIterator aiter(fst, s); - aiter.SetFlags(kArcWeightValue | kArcNoCache, kArcFlags); - for (; !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - sum = LogPlus(sum, arc.weight); - // Stores cumulative weight distribution per arc_period_. - if (++narcs % arc_period_ == 0) weights.push_back(sum); - } - } - } - data_->SetData(&weights, &weight_positions); - } - - bool Error() const { return error_; } - - std::shared_ptr GetData() const { return data_; } - - private: - static double LogPosExp(double x) { - return x == FloatLimits::PosInfinity() ? 0.0 - : log(1.0F + exp(-x)); - } - - static double LogMinusExp(double x) { - return x == FloatLimits::PosInfinity() ? 0.0 - : log(1.0F - exp(-x)); - } - - Weight LogPlus(Weight w, Weight v) const { - if (w == Weight::Zero()) { - return v; - } - const auto f1 = to_log_weight_(w).Value(); - const auto f2 = to_log_weight_(v).Value(); - if (f1 > f2) { - return to_weight_(Log64Weight(f2 - LogPosExp(f1 - f2))); - } else { - return to_weight_(Log64Weight(f1 - LogPosExp(f2 - f1))); - } - } - - double LogPlus(double f1, Weight v) const { - const auto f2 = to_log_weight_(v).Value(); - if (f1 == FloatLimits::PosInfinity()) { - return f2; - } else if (f1 > f2) { - return f2 - LogPosExp(f1 - f2); - } else { - return f1 - LogPosExp(f2 - f1); - } - } - - // Assumes f1 < f2. - Weight LogMinus(double f1, double f2) const { - if (f2 == FloatLimits::PosInfinity()) { - return to_weight_(Log64Weight(f1)); - } else { - return to_weight_(Log64Weight(f1 - LogMinusExp(f2 - f1))); - } - } - - const WeightConvert to_log_weight_{}; - const WeightConvert to_weight_{}; - const ssize_t arc_limit_; // Minimum number of arcs to pre-compute state. - const ssize_t arc_period_; // Saves cumulative weights per arc_period_. - std::shared_ptr data_; - const double *state_weights_; - bool error_; - - FastLogAccumulator &operator=(const FastLogAccumulator &) = delete; -}; - -// Stores shareable data for cache log accumulator copies. All copies share the -// same cache. -template -class CacheLogAccumulatorData { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - CacheLogAccumulatorData(bool gc, size_t gc_limit) - : cache_gc_(gc), cache_limit_(gc_limit), cache_size_(0) {} - - CacheLogAccumulatorData(const CacheLogAccumulatorData &data) - : cache_gc_(data.cache_gc_), - cache_limit_(data.cache_limit_), - cache_size_(0) {} - - bool CacheDisabled() const { return cache_gc_ && cache_limit_ == 0; } - - std::vector *GetWeights(StateId s) { - if (auto it = cache_.find(s); it != cache_.end()) { - it->second.recent = true; - return it->second.weights.get(); - } else { - return nullptr; - } - } - - void AddWeights(StateId s, std::unique_ptr> weights) { - if (cache_gc_ && cache_size_ >= cache_limit_) GC(false); - if (cache_gc_) cache_size_ += weights->capacity() * sizeof(double); - cache_.emplace(s, CacheState(std::move(weights), true)); - } - - private: - // Cached information for a given state. - struct CacheState { - std::unique_ptr> weights; // Accumulated weights. - bool recent; // Has this state been accessed since last GC? - - CacheState(std::unique_ptr> weights, bool recent) - : weights(std::move(weights)), recent(recent) {} - }; - - // Garbage collect: Deletes from cache states that have not been accessed - // since the last GC ('free_recent = false') until 'cache_size_' is 2/3 of - // 'cache_limit_'. If it does not free enough memory, start deleting - // recently accessed states. - void GC(bool free_recent) { - auto cache_target = (2 * cache_limit_) / 3 + 1; - auto it = cache_.begin(); - while (it != cache_.end() && cache_size_ > cache_target) { - auto &cs = it->second; - if (free_recent || !cs.recent) { - cache_size_ -= cs.weights->capacity() * sizeof(double); - cache_.erase(it++); - } else { - cs.recent = false; - ++it; - } - } - if (!free_recent && cache_size_ > cache_target) GC(true); - } - - std::unordered_map cache_; // Cache. - bool cache_gc_; // Enables garbage collection. - size_t cache_limit_; // # of bytes cached. - size_t cache_size_; // # of bytes allowed before GC. - - CacheLogAccumulatorData &operator=(const CacheLogAccumulatorData &) = delete; -}; - -// This class accumulates arc weights using the log semiring Plus() has a -// WeightConvert specialization to and from log64 weights. It is similar to the -// FastLogAccumator. However here, the accumulated weights are pre-computed and -// stored only for the states that are visited. The member function Init(fst) -// has to be called to setup this accumulator. Space complexity is O(gc_limit). -template -class CacheLogAccumulator { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit CacheLogAccumulator(ssize_t arc_limit = 10, bool gc = false, - size_t gc_limit = 10 * 1024 * 1024) - : arc_limit_(arc_limit), - data_(std::make_shared>(gc, gc_limit)), - s_(kNoStateId), - error_(false) {} - - CacheLogAccumulator(const CacheLogAccumulator &acc, bool safe = false) - : arc_limit_(acc.arc_limit_), - fst_(acc.fst_ ? acc.fst_->Copy() : nullptr), - data_(safe ? std::make_shared>(*acc.data_) - : acc.data_), - s_(kNoStateId), - error_(acc.error_) {} - - // Argument arc_limit specifies the minimum number of arcs to pre-compute. - void Init(const Fst &fst, bool copy = false) { - if (!copy && fst_) { - FSTERROR() << "CacheLogAccumulator: Initialization error"; - error_ = true; - return; - } - fst_.reset(fst.Copy()); - } - - void SetState(StateId s, int depth = 0) { - if (s == s_) return; - s_ = s; - if (data_->CacheDisabled() || error_) { - weights_ = nullptr; - return; - } - if (!fst_) { - FSTERROR() << "CacheLogAccumulator::SetState: Incorrectly initialized"; - error_ = true; - weights_ = nullptr; - return; - } - weights_ = data_->GetWeights(s); - if ((weights_ == nullptr) && (fst_->NumArcs(s) >= arc_limit_)) { - auto weights = std::make_unique>(); - weights->reserve(fst_->NumArcs(s) + 1); - weights->push_back(FloatLimits::PosInfinity()); - // `weights` holds a reference to the weight vector, whose ownership is - // transferred to `data_`. - weights_ = weights.get(); - data_->AddWeights(s, std::move(weights)); - } - } - - Weight Sum(Weight w, Weight v) { return LogPlus(w, v); } - - template - Weight Sum(Weight w, ArcIter *aiter, ssize_t begin, ssize_t end) { - if (weights_ == nullptr) { - auto sum = w; - aiter->Seek(begin); - for (auto pos = begin; pos < end; aiter->Next(), ++pos) { - sum = LogPlus(sum, aiter->Value().weight); - } - return sum; - } else { - Extend(end, aiter); - const auto &f1 = (*weights_)[end]; - const auto &f2 = (*weights_)[begin]; - if (f1 < f2) { - return LogPlus(w, LogMinus(f1, f2)); - } else { - // Commented out for efficiency; adds Zero(). - /* - auto sum = w; - // Explicitly computes if cumulative sum lacks precision. - aiter->Seek(begin); - for (auto pos = begin; pos < end; aiter->Next(), ++pos) { - sum = LogPlus(sum, aiter->Value().weight); - } - return sum; - */ - return w; - } - } - } - - // Returns first position from aiter->Position() whose accumulated - // value is greater or equal to w (w.r.t. Zero() < One()). The - // iterator may be repositioned. - template - size_t LowerBound(Weight w, ArcIter *aiter) { - const auto f = to_log_weight_(w).Value(); - auto pos = aiter->Position(); - if (weights_) { - Extend(fst_->NumArcs(s_), aiter); - return std::lower_bound(weights_->begin() + pos + 1, weights_->end(), f, - std::greater()) - - weights_->begin() - 1; - } else { - size_t n = 0; - auto x = FloatLimits::PosInfinity(); - for (aiter->Reset(); !aiter->Done(); aiter->Next(), ++n) { - x = LogPlus(x, aiter->Value().weight); - if (n >= pos && x <= f) break; - } - return n; - } - } - - bool Error() const { return error_; } - - private: - double LogPosExp(double x) { - return x == FloatLimits::PosInfinity() ? 0.0 - : log(1.0F + exp(-x)); - } - - double LogMinusExp(double x) { - return x == FloatLimits::PosInfinity() ? 0.0 - : log(1.0F - exp(-x)); - } - - Weight LogPlus(Weight w, Weight v) { - if (w == Weight::Zero()) { - return v; - } - const auto f1 = to_log_weight_(w).Value(); - const auto f2 = to_log_weight_(v).Value(); - if (f1 > f2) { - return to_weight_(Log64Weight(f2 - LogPosExp(f1 - f2))); - } else { - return to_weight_(Log64Weight(f1 - LogPosExp(f2 - f1))); - } - } - - double LogPlus(double f1, Weight v) { - const auto f2 = to_log_weight_(v).Value(); - if (f1 == FloatLimits::PosInfinity()) { - return f2; - } else if (f1 > f2) { - return f2 - LogPosExp(f1 - f2); - } else { - return f1 - LogPosExp(f2 - f1); - } - } - - // Assumes f1 < f2. - Weight LogMinus(double f1, double f2) { - if (f2 == FloatLimits::PosInfinity()) { - return to_weight_(Log64Weight(f1)); - } else { - return to_weight_(Log64Weight(f1 - LogMinusExp(f2 - f1))); - } - } - - // Extends weights up to index 'end'. - template - void Extend(ssize_t end, ArcIter *aiter) { - if (weights_->size() <= end) { - for (aiter->Seek(weights_->size() - 1); weights_->size() <= end; - aiter->Next()) { - weights_->push_back(LogPlus(weights_->back(), aiter->Value().weight)); - } - } - } - - const WeightConvert to_log_weight_{}; - const WeightConvert to_weight_{}; - ssize_t arc_limit_; // Minimum # of arcs to cache a state. - std::vector *weights_; // Accumulated weights for cur. state. - // Pointee owned by `data_`. - std::unique_ptr> fst_; // Input FST. - std::shared_ptr> data_; // Cache data. - StateId s_; // Current state. - bool error_; -}; - -// Stores shareable data for replace accumulator copies. -template -class ReplaceAccumulatorData { - public: - using Arc = typename Accumulator::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using StateTable = T; - using StateTuple = typename StateTable::StateTuple; - - ReplaceAccumulatorData() : state_table_(nullptr) {} - - explicit ReplaceAccumulatorData( - std::vector> &&accumulators) - : state_table_(nullptr), accumulators_(std::move(accumulators)) {} - - void Init(const std::vector *>> &fst_tuples, - const StateTable *state_table) { - state_table_ = state_table; - accumulators_.resize(fst_tuples.size()); - for (Label i = 0; i < accumulators_.size(); ++i) { - if (!accumulators_[i]) { - accumulators_[i] = std::make_unique(); - accumulators_[i]->Init(*(fst_tuples[i].second)); - } - fst_array_.emplace_back(fst_tuples[i].second->Copy()); - } - } - - const StateTuple &GetTuple(StateId s) const { return state_table_->Tuple(s); } - - Accumulator *GetAccumulator(size_t i) { return accumulators_[i].get(); } - - const Fst *GetFst(size_t i) const { return fst_array_[i].get(); } - - private: - const StateTable *state_table_; - std::vector> accumulators_; - std::vector>> fst_array_; -}; - -// This class accumulates weights in a ReplaceFst. The 'Init' method takes as -// input the argument used to build the ReplaceFst and the ReplaceFst state -// table. It uses accumulators of type 'Accumulator' in the underlying FSTs. -template > -class ReplaceAccumulator { - public: - using Arc = typename Accumulator::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using StateTable = T; - using StateTuple = typename StateTable::StateTuple; - using Weight = typename Arc::Weight; - - ReplaceAccumulator() - : init_(false), - data_(std::make_shared< - ReplaceAccumulatorData>()), - error_(false) {} - - explicit ReplaceAccumulator( - std::vector> &&accumulators) - : init_(false), - data_(std::make_shared>( - std::move(accumulators))), - error_(false) {} - - ReplaceAccumulator(const ReplaceAccumulator &acc, - bool safe = false) - : init_(acc.init_), data_(acc.data_), error_(acc.error_) { - if (!init_) { - FSTERROR() << "ReplaceAccumulator: Can't copy unintialized accumulator"; - } - if (safe) FSTERROR() << "ReplaceAccumulator: Safe copy not supported"; - } - - // Does not take ownership of the state table, the state table is owned by - // the ReplaceFst. - void Init(const std::vector *>> &fst_tuples, - const StateTable *state_table) { - init_ = true; - data_->Init(fst_tuples, state_table); - } - - // Method required by LookAheadMatcher. However, ReplaceAccumulator needs to - // be initialized by calling the Init method above before being passed to - // LookAheadMatcher. - // - // TODO(allauzen): Revisit this. Consider creating a method - // Init(const ReplaceFst&, bool) and using friendship to get access - // to the innards of ReplaceFst. - void Init(const Fst &fst, bool copy = false) { - if (!init_) { - FSTERROR() << "ReplaceAccumulator::Init: Accumulator needs to be" - << " initialized before being passed to LookAheadMatcher"; - error_ = true; - } - } - - void SetState(StateId s) { - if (!init_) { - FSTERROR() << "ReplaceAccumulator::SetState: Incorrectly initialized"; - error_ = true; - return; - } - auto tuple = data_->GetTuple(s); - fst_id_ = tuple.fst_id - 1; // Replace FST ID is 1-based. - data_->GetAccumulator(fst_id_)->SetState(tuple.fst_state); - if ((tuple.prefix_id != 0) && - (data_->GetFst(fst_id_)->Final(tuple.fst_state) != Weight::Zero())) { - offset_ = 1; - offset_weight_ = data_->GetFst(fst_id_)->Final(tuple.fst_state); - } else { - offset_ = 0; - offset_weight_ = Weight::Zero(); - } - aiter_ = std::make_unique>>(*data_->GetFst(fst_id_), - tuple.fst_state); - } - - Weight Sum(Weight w, Weight v) { - if (error_) return Weight::NoWeight(); - return data_->GetAccumulator(fst_id_)->Sum(w, v); - } - - template - Weight Sum(Weight w, ArcIter *aiter, ssize_t begin, ssize_t end) { - if (error_) return Weight::NoWeight(); - auto sum = begin == end ? Weight::Zero() - : data_->GetAccumulator(fst_id_)->Sum( - w, aiter_.get(), begin ? begin - offset_ : 0, - end - offset_); - if (begin == 0 && end != 0 && offset_ > 0) sum = Sum(offset_weight_, sum); - return sum; - } - - bool Error() const { return error_; } - - private: - bool init_; - std::shared_ptr> data_; - Label fst_id_; - size_t offset_; - Weight offset_weight_; - std::unique_ptr>> aiter_; - bool error_; -}; - -// SafeReplaceAccumulator accumulates weights in a ReplaceFst and copies of it -// are always thread-safe copies. -template -class SafeReplaceAccumulator { - public: - using Arc = typename Accumulator::Arc; - using StateId = typename Arc::StateId; - using Label = typename Arc::Label; - using Weight = typename Arc::Weight; - using StateTable = T; - using StateTuple = typename StateTable::StateTuple; - - SafeReplaceAccumulator() = default; - - SafeReplaceAccumulator(const SafeReplaceAccumulator ©, bool safe) - : SafeReplaceAccumulator(copy) {} - - explicit SafeReplaceAccumulator( - const std::vector &accumulators) { - for (const auto &accumulator : accumulators) { - accumulators_.emplace_back(accumulator, true); - } - } - - void Init(const std::vector *>> &fst_tuples, - const StateTable *state_table) { - state_table_ = state_table; - for (Label i = 0; i < fst_tuples.size(); ++i) { - if (i == accumulators_.size()) { - accumulators_.resize(accumulators_.size() + 1); - accumulators_[i].Init(*(fst_tuples[i].second)); - } - fst_array_.emplace_back(fst_tuples[i].second->Copy(true)); - } - init_ = true; - } - - void Init(const Fst &fst, bool copy = false) { - if (!init_) { - FSTERROR() << "SafeReplaceAccumulator::Init: Accumulator needs to be" - << " initialized before being passed to LookAheadMatcher"; - error_ = true; - } - } - - void SetState(StateId s) { - auto tuple = state_table_->Tuple(s); - fst_id_ = tuple.fst_id - 1; // Replace FST ID is 1-based - GetAccumulator(fst_id_)->SetState(tuple.fst_state); - offset_ = 0; - offset_weight_ = Weight::Zero(); - const auto final_weight = GetFst(fst_id_)->Final(tuple.fst_state); - if ((tuple.prefix_id != 0) && (final_weight != Weight::Zero())) { - offset_ = 1; - offset_weight_ = final_weight; - } - aiter_.Set(*GetFst(fst_id_), tuple.fst_state); - } - - Weight Sum(Weight w, Weight v) { - if (error_) return Weight::NoWeight(); - return GetAccumulator(fst_id_)->Sum(w, v); - } - - template - Weight Sum(Weight w, ArcIter *aiter, ssize_t begin, ssize_t end) { - if (error_) return Weight::NoWeight(); - if (begin == end) return Weight::Zero(); - auto sum = GetAccumulator(fst_id_)->Sum( - w, aiter_.get(), begin ? begin - offset_ : 0, end - offset_); - if (begin == 0 && end != 0 && offset_ > 0) { - sum = Sum(offset_weight_, sum); - } - return sum; - } - - bool Error() const { return error_; } - - private: - class ArcIteratorPtr { - public: - ArcIteratorPtr() = default; - - ArcIteratorPtr(const ArcIteratorPtr ©) {} - - void Set(const Fst &fst, StateId state_id) { - ptr_ = std::make_unique>>(fst, state_id); - } - - ArcIterator> *get() { return ptr_.get(); } - - private: - std::unique_ptr>> ptr_; - }; - - Accumulator *GetAccumulator(size_t i) { return &accumulators_[i]; } - - const Fst *GetFst(size_t i) const { return fst_array_[i].get(); } - - const StateTable *state_table_; - std::vector accumulators_; - std::vector>> fst_array_; - ArcIteratorPtr aiter_; - bool init_ = false; - bool error_ = false; - Label fst_id_; - size_t offset_; - Weight offset_weight_; -}; - -} // namespace fst - -#endif // FST_ACCUMULATOR_H_ diff --git a/contrib/fstlib/fst/add-on.h b/contrib/fstlib/fst/add-on.h deleted file mode 100644 index 7110502..0000000 --- a/contrib/fstlib/fst/add-on.h +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST implementation class to attach an arbitrary object with a read/write -// method to an FST and its file representation. The FST is given a new type -// name. - -#ifndef FST_ADD_ON_H_ -#define FST_ADD_ON_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -// Identifies stream data as an add-on FST. -inline constexpr int32_t kAddOnMagicNumber = 446681434; - -// Nothing to save. -class NullAddOn { - public: - NullAddOn() = default; - - static NullAddOn *Read(std::istream &strm, const FstReadOptions &opts) { - return new NullAddOn(); - } - - bool Write(std::ostream &ostrm, const FstWriteOptions &opts) const { - return true; - } -}; - -// Create a new add-on from a pair of add-ons. -template -class AddOnPair { - public: - // Argument reference count incremented. - AddOnPair(std::shared_ptr a1, std::shared_ptr a2) - : a1_(std::move(a1)), a2_(std::move(a2)) {} - - const A1 *First() const { return a1_.get(); } - - const A2 *Second() const { return a2_.get(); } - - std::shared_ptr SharedFirst() const { return a1_; } - - std::shared_ptr SharedSecond() const { return a2_; } - - static AddOnPair *Read(std::istream &istrm, const FstReadOptions &opts) { - bool have_addon1 = false; - ReadType(istrm, &have_addon1); - std::unique_ptr a1; - if (have_addon1) a1 = fst::WrapUnique(A1::Read(istrm, opts)); - - bool have_addon2 = false; - ReadType(istrm, &have_addon2); - std::unique_ptr a2; - if (have_addon2) a2 = fst::WrapUnique(A2::Read(istrm, opts)); - - return new AddOnPair(std::move(a1), std::move(a2)); - } - - bool Write(std::ostream &ostrm, const FstWriteOptions &opts) const { - bool have_addon1 = a1_ != nullptr; - WriteType(ostrm, have_addon1); - if (have_addon1) a1_->Write(ostrm, opts); - bool have_addon2 = a2_ != nullptr; - WriteType(ostrm, have_addon2); - if (have_addon2) a2_->Write(ostrm, opts); - return true; - } - - private: - std::shared_ptr a1_; - std::shared_ptr a2_; -}; - -namespace internal { - -// Adds an object of type T to an FST. T must support: -// -// T* Read(std::istream &); -// bool Write(std::ostream &); -// -// The resulting type is a new FST implementation. -template -class AddOnImpl : public FstImpl { - public: - using FstType = FST; - using Arc = typename FST::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetType; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - using FstImpl::SetProperties; - using FstImpl::WriteHeader; - - // We make a thread-safe copy of the FST by default since an FST - // implementation is expected to not share mutable data between objects. - AddOnImpl(const FST &fst, std::string_view type, - std::shared_ptr t = nullptr) - : fst_(fst, true), t_(std::move(t)) { - SetType(type); - SetProperties(fst_.Properties(kFstProperties, false)); - SetInputSymbols(fst_.InputSymbols()); - SetOutputSymbols(fst_.OutputSymbols()); - } - - // Conversion from const Fst & to F always copies the underlying - // implementation. - AddOnImpl(const Fst &fst, std::string_view type, - std::shared_ptr t = nullptr) - : fst_(fst), t_(std::move(t)) { - SetType(type); - SetProperties(fst_.Properties(kFstProperties, false)); - SetInputSymbols(fst_.InputSymbols()); - SetOutputSymbols(fst_.OutputSymbols()); - } - - // We make a thread-safe copy of the FST by default since an FST - // implementation is expected to not share mutable data between objects. - AddOnImpl(const AddOnImpl &impl) : fst_(impl.fst_, true), t_(impl.t_) { - SetType(impl.Type()); - SetProperties(fst_.Properties(kCopyProperties, false)); - SetInputSymbols(fst_.InputSymbols()); - SetOutputSymbols(fst_.OutputSymbols()); - } - - StateId Start() const { return fst_.Start(); } - - Weight Final(StateId s) const { return fst_.Final(s); } - - size_t NumArcs(StateId s) const { return fst_.NumArcs(s); } - - size_t NumInputEpsilons(StateId s) const { return fst_.NumInputEpsilons(s); } - - size_t NumOutputEpsilons(StateId s) const { - return fst_.NumOutputEpsilons(s); - } - - size_t NumStates() const { return fst_.NumStates(); } - - static AddOnImpl *Read(std::istream &strm, const FstReadOptions &opts) { - FstReadOptions nopts(opts); - FstHeader hdr; - if (!nopts.header) { - hdr.Read(strm, nopts.source); - nopts.header = &hdr; - } - // Using `new` to access private constructor for `AddOnImpl`. - auto impl = fst::WrapUnique(new AddOnImpl(nopts.header->FstType())); - if (!impl->ReadHeader(strm, nopts, kMinFileVersion, &hdr)) return nullptr; - impl.reset(); - int32_t magic_number = 0; - ReadType(strm, &magic_number); // Ensures this is an add-on FST. - if (magic_number != kAddOnMagicNumber) { - LOG(ERROR) << "AddOnImpl::Read: Bad add-on header: " << nopts.source; - return nullptr; - } - FstReadOptions fopts(opts); - fopts.header = nullptr; // Contained header was written out. - std::unique_ptr fst(FST::Read(strm, fopts)); - if (!fst) return nullptr; - std::shared_ptr t; - bool have_addon = false; - ReadType(strm, &have_addon); - if (have_addon) { // Reads add-on object if present. - t = std::shared_ptr(T::Read(strm, fopts)); - if (!t) return nullptr; - } - return new AddOnImpl(*fst, nopts.header->FstType(), t); - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const { - FstHeader hdr; - FstWriteOptions nopts(opts); - nopts.write_isymbols = false; // Allows contained FST to hold any symbols. - nopts.write_osymbols = false; - WriteHeader(strm, nopts, kFileVersion, &hdr); - WriteType(strm, kAddOnMagicNumber); // Ensures this is an add-on FST. - FstWriteOptions fopts(opts); - fopts.write_header = true; // Forces writing contained header. - if (!fst_.Write(strm, fopts)) return false; - bool have_addon = !!t_; - WriteType(strm, have_addon); - // Writes add-on object if present. - if (have_addon) t_->Write(strm, opts); - return true; - } - - void InitStateIterator(StateIteratorData *data) const { - fst_.InitStateIterator(data); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) const { - fst_.InitArcIterator(s, data); - } - - FST &GetFst() { return fst_; } - - const FST &GetFst() const { return fst_; } - - const T *GetAddOn() const { return t_.get(); } - - std::shared_ptr GetSharedAddOn() const { return t_; } - - void SetAddOn(std::shared_ptr t) { t_ = t; } - - private: - explicit AddOnImpl(std::string_view type) : t_() { - SetType(type); - SetProperties(kExpanded); - } - - // Current file format version. - static constexpr int kFileVersion = 1; - // Minimum file format version supported. - static constexpr int kMinFileVersion = 1; - - FST fst_; - std::shared_ptr t_; - - AddOnImpl &operator=(const AddOnImpl &) = delete; -}; - -} // namespace internal -} // namespace fst - -#endif // FST_ADD_ON_H_ diff --git a/contrib/fstlib/fst/arc-arena.h b/contrib/fstlib/fst/arc-arena.h deleted file mode 100644 index 25579b2..0000000 --- a/contrib/fstlib/fst/arc-arena.h +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Allocators for contiguous arrays of arcs. - -#ifndef FST_ARC_ARENA_H_ -#define FST_ARC_ARENA_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace fst { - -// ArcArena is used for fast allocation of contiguous arrays of arcs. -// -// To create an arc array: -// for each state: -// for each arc: -// arena.PushArc(); -// // Commits these arcs and returns pointer to them. -// Arc *arcs = arena.GetArcs(); -// -// OR -// -// arena.DropArcs(); // Throws away current arcs, reuse the space. -// -// The arcs returned are guaranteed to be contiguous and the pointer returned -// will never be invalidated until the arena is cleared for reuse. -// -// The contents of the arena can be released with a call to arena.Clear() after -// which the arena will restart with an initial allocation capable of holding at -// least all of the arcs requested in the last usage before Clear() making -// subsequent uses of the Arena more efficient. -// -// The max_retained_size option can limit the amount of arc space requested on -// Clear() to avoid excess growth from intermittent high usage. -template -class ArcArena { - public: - explicit ArcArena(size_t block_size = 256, size_t max_retained_size = 1e6) - : block_size_(block_size), max_retained_size_(max_retained_size) { - blocks_.emplace_back(MakeSharedBlock(block_size_)); - first_block_size_ = block_size_; - total_size_ = block_size_; - arcs_ = blocks_.back().get(); - end_ = arcs_ + block_size_; - next_ = arcs_; - } - - ArcArena(const ArcArena ©) - : arcs_(copy.arcs_), - next_(copy.next_), - end_(copy.end_), - block_size_(copy.block_size_), - first_block_size_(copy.first_block_size_), - total_size_(copy.total_size_), - max_retained_size_(copy.max_retained_size_), - blocks_(copy.blocks_) { - NewBlock(block_size_); - } - - void ReserveArcs(size_t n) { - if (next_ + n < end_) return; - NewBlock(n); - } - - void PushArc(const Arc &arc) { - if (next_ == end_) { - size_t length = next_ - arcs_; - NewBlock(length * 2); - } - *next_ = arc; - ++next_; - } - - const Arc *GetArcs() { - const auto *arcs = arcs_; - arcs_ = next_; - return arcs; - } - - void DropArcs() { next_ = arcs_; } - - size_t Size() { return total_size_; } - - void Clear() { - blocks_.resize(1); - if (total_size_ > first_block_size_) { - first_block_size_ = std::min(max_retained_size_, total_size_); - blocks_.back() = MakeSharedBlock(first_block_size_); - } - total_size_ = first_block_size_; - arcs_ = blocks_.back().get(); - end_ = arcs_ + first_block_size_; - next_ = arcs_; - } - - private: - // Allocates a new block with capacity of at least n or block_size, - // copying incomplete arc sequence from old block to new block. - void NewBlock(size_t n) { - const auto length = next_ - arcs_; - const auto new_block_size = std::max(n, block_size_); - total_size_ += new_block_size; - blocks_.emplace_back(MakeSharedBlock(new_block_size)); - std::copy(arcs_, next_, blocks_.back().get()); - arcs_ = blocks_.back().get(); - next_ = arcs_ + length; - end_ = arcs_ + new_block_size; - } - - std::shared_ptr MakeSharedBlock(size_t size) { - return std::shared_ptr(new Arc[size]); - } - - Arc *arcs_; - Arc *next_; - const Arc *end_; - size_t block_size_; - size_t first_block_size_; - size_t total_size_; - size_t max_retained_size_; - std::list> blocks_; -}; - -// ArcArenaStateStore uses a resusable ArcArena to store arc arrays and does not -// require that the Expander call ReserveArcs first. -// -// TODO(tombagby): Make cache type configurable. -// TODO(tombagby): Provide ThreadLocal/Concurrent configuration. -template -class ArcArenaStateStore { - public: - using Arc = A; - using Weight = typename Arc::Weight; - using StateId = typename Arc::StateId; - - class State { - public: - Weight Final() const { return final_weight_; } - - size_t NumInputEpsilons() const { return niepsilons_; } - - size_t NumOutputEpsilons() const { return noepsilons_; } - - size_t NumArcs() const { return narcs_; } - - const Arc &GetArc(size_t n) const { return arcs_[n]; } - - const Arc *Arcs() const { return arcs_; } - - int *MutableRefCount() const { return nullptr; } - - private: - State(Weight final_weight, int32_t niepsilons, int32_t noepsilons, - int32_t narcs, const Arc *arcs) - : final_weight_(std::move(final_weight)), - niepsilons_(niepsilons), - noepsilons_(noepsilons), - narcs_(narcs), - arcs_(arcs) {} - - Weight final_weight_; - size_t niepsilons_; - size_t noepsilons_; - size_t narcs_; - const Arc *arcs_; - - friend class ArcArenaStateStore; - }; - - template - State *FindOrExpand(Expander &expander, StateId state_id) { - const auto &[it, success] = cache_.emplace(state_id, nullptr); - if (!success) return it->second; - // Needs a new state. - StateBuilder builder(&arena_); - expander.Expand(state_id, &builder); - const auto arcs = arena_.GetArcs(); - size_t narcs = builder.narcs_; - size_t niepsilons = 0; - size_t noepsilons = 0; - for (size_t i = 0; i < narcs; ++i) { - if (arcs[i].ilabel == 0) ++niepsilons; - if (arcs[i].olabel == 0) ++noepsilons; - } - states_.emplace_back( - State(builder.final_weight_, niepsilons, noepsilons, narcs, arcs)); - // Places it in the cache. - auto state = &states_.back(); - it->second = state; - return state; - } - - State *Find(StateId state_id) const { - auto it = cache_.find(state_id); - return (it == cache_.end()) ? nullptr : it->second; - } - - private: - class StateBuilder { - public: - explicit StateBuilder(ArcArena *arena) - : arena_(arena), final_weight_(Weight::Zero()), narcs_(0) {} - - void SetFinal(Weight weight) { final_weight_ = std::move(weight); } - - void ReserveArcs(size_t n) { arena_->ReserveArcs(n); } - - void AddArc(const Arc &arc) { - ++narcs_; - arena_->PushArc(arc); - } - - private: - friend class ArcArenaStateStore; - - ArcArena *arena_; - Weight final_weight_; - size_t narcs_; - }; - - std::unordered_map cache_; - std::deque states_; - ArcArena arena_; -}; - -} // namespace fst - -#endif // FST_ARC_ARENA_H_ diff --git a/contrib/fstlib/fst/arc-map.h b/contrib/fstlib/fst/arc-map.h deleted file mode 100644 index 4474db0..0000000 --- a/contrib/fstlib/fst/arc-map.h +++ /dev/null @@ -1,1322 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to map over/transform arcs e.g., change semirings or -// implement project/invert. Consider using when operation does -// not change the number of arcs (except possibly superfinal arcs). - -#ifndef FST_ARC_MAP_H_ -#define FST_ARC_MAP_H_ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Determines how final weights are mapped. -enum MapFinalAction { - // A final weight is mapped into a final weight. An error is raised if this - // is not possible. - MAP_NO_SUPERFINAL, - // A final weight is mapped to an arc to the superfinal state when the result - // cannot be represented as a final weight. The superfinal state will be - // added only if it is needed. - MAP_ALLOW_SUPERFINAL, - // A final weight is mapped to an arc to the superfinal state unless the - // result can be represented as a final weight of weight Zero(). The - // superfinal state is always added (if the input is not the empty FST). - MAP_REQUIRE_SUPERFINAL -}; - -// Determines how symbol tables are mapped. -enum MapSymbolsAction { - // Symbols should be cleared in the result by the map. - MAP_CLEAR_SYMBOLS, - // Symbols should be copied from the input FST by the map. - MAP_COPY_SYMBOLS, - // Symbols should not be modified in the result by the map itself. - // (They may set by the mapper). - MAP_NOOP_SYMBOLS -}; - -// The ArcMapper interfaces defines how arcs and final weights are mapped. -// This is useful for implementing operations that apply to each arc separately -// and do not change the number of arcs (except possibly superfinal arcs). -// -// template -// class ArcMapper { -// public: -// using FromArc = A; -// using ToArc = B; -// -// // Maps an arc type FromArc to arc type ToArc. -// ToArc operator()(const FromArc &arc); -// -// // Specifies final action the mapper requires (see above). -// // The mapper will be passed final weights as arcs of the form -// // Arc(0, 0, weight, kNoStateId). -// MapFinalAction FinalAction() const; -// -// // 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 FSTs's known properties. -// uint64_t Properties(uint64_t props) const; -// }; -// -// The ArcMap functions and classes below will use the FinalAction() -// method of the mapper to determine how to treat final weights, e.g., whether -// to add a superfinal state. They will use the Properties() method to set the -// result FST properties. -// -// We include a various 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. This is the case with the EncodeMapper, which is reused -// during decoding. 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 its Fst input. -template -void ArcMap(MutableFst *fst, C *mapper) { - using FromArc = A; - using ToArc = A; - using Weight = typename FromArc::Weight; - 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); - const auto final_action = mapper->FinalAction(); - auto superfinal = kNoStateId; - if (final_action == MAP_REQUIRE_SUPERFINAL) { - superfinal = fst->AddState(); - fst->SetFinal(superfinal); - } - for (StateIterator> siter(*fst); !siter.Done(); - siter.Next()) { - const auto state = siter.Value(); - for (MutableArcIterator> aiter(fst, state); - !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - aiter.SetValue((*mapper)(arc)); - } - switch (final_action) { - case MAP_NO_SUPERFINAL: - default: { - const FromArc arc(0, 0, fst->Final(state), kNoStateId); - const auto final_arc = (*mapper)(arc); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) { - FSTERROR() << "ArcMap: Non-zero arc labels for superfinal arc"; - fst->SetProperties(kError, kError); - } - fst->SetFinal(state, final_arc.weight); - break; - } - case MAP_ALLOW_SUPERFINAL: { - if (state != superfinal) { - const FromArc arc(0, 0, fst->Final(state), kNoStateId); - auto final_arc = (*mapper)(arc); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) { - // Add a superfinal state if not already done. - if (superfinal == kNoStateId) { - superfinal = fst->AddState(); - fst->SetFinal(superfinal); - } - final_arc.nextstate = superfinal; - fst->AddArc(state, std::move(final_arc)); - fst->SetFinal(state, Weight::Zero()); - } else { - fst->SetFinal(state, final_arc.weight); - } - } - break; - } - case MAP_REQUIRE_SUPERFINAL: { - if (state != superfinal) { - const FromArc arc(0, 0, fst->Final(state), kNoStateId); - const auto final_arc = (*mapper)(arc); - if (final_arc.ilabel != 0 || final_arc.olabel != 0 || - final_arc.weight != Weight::Zero()) { - fst->AddArc(state, ToArc(final_arc.ilabel, final_arc.olabel, - final_arc.weight, superfinal)); - } - fst->SetFinal(state, Weight::Zero()); - } - break; - } - } - } - fst->SetProperties(mapper->Properties(props), kFstProperties); -} - -// Maps an arc type A using a mapper function object C, passed by value. This -// version modifies its FST input. -template -void ArcMap(MutableFst *fst, C mapper) { - ArcMap(fst, &mapper); -} - -// Maps an arc type A to an arc type B using mapper function object C, -// passed by pointer. This version writes the mapped input FST to an -// output MutableFst. -template -void ArcMap(const Fst &ifst, MutableFst *ofst, C *mapper) { - using FromArc = A; - using StateId = typename FromArc::StateId; - 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; - } - const auto final_action = mapper->FinalAction(); - if (std::optional num_states = ifst.NumStatesIfKnown()) { - ofst->ReserveStates(*num_states + - (final_action == MAP_NO_SUPERFINAL ? 0 : 1)); - } - // Adds all states. - for (StateIterator> siter(ifst); !siter.Done(); siter.Next()) { - ofst->AddState(); - } - StateId superfinal = kNoStateId; - if (final_action == MAP_REQUIRE_SUPERFINAL) { - superfinal = ofst->AddState(); - ofst->SetFinal(superfinal); - } - for (StateIterator> siter(ifst); !siter.Done(); siter.Next()) { - StateId s = siter.Value(); - if (s == ifst.Start()) ofst->SetStart(s); - ofst->ReserveArcs( - s, ifst.NumArcs(s) + (final_action != MAP_NO_SUPERFINAL ? 1 : 0)); - for (ArcIterator> aiter(ifst, s); !aiter.Done(); aiter.Next()) { - ofst->AddArc(s, (*mapper)(aiter.Value())); - } - switch (final_action) { - case MAP_NO_SUPERFINAL: - default: { - B final_arc = (*mapper)(A(0, 0, ifst.Final(s), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) { - FSTERROR() << "ArcMap: Non-zero arc labels for superfinal arc"; - ofst->SetProperties(kError, kError); - } - ofst->SetFinal(s, final_arc.weight); - break; - } - case MAP_ALLOW_SUPERFINAL: { - B final_arc = (*mapper)(A(0, 0, ifst.Final(s), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) { - // Add a superfinal state if not already done. - if (superfinal == kNoStateId) { - superfinal = ofst->AddState(); - ofst->SetFinal(superfinal); - } - final_arc.nextstate = superfinal; - ofst->AddArc(s, std::move(final_arc)); - ofst->SetFinal(s, B::Weight::Zero()); - } else { - ofst->SetFinal(s, final_arc.weight); - } - break; - } - case MAP_REQUIRE_SUPERFINAL: { - B final_arc = (*mapper)(A(0, 0, ifst.Final(s), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0 || - final_arc.weight != B::Weight::Zero()) { - ofst->AddArc(s, B(final_arc.ilabel, final_arc.olabel, - final_arc.weight, superfinal)); - } - ofst->SetFinal(s, B::Weight::Zero()); - break; - } - } - } - 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 function -// object C, passed by value. This version writes the mapped input -// Fst to an output MutableFst. -template -void ArcMap(const Fst &ifst, MutableFst *ofst, C mapper) { - ArcMap(ifst, ofst, &mapper); -} - -struct ArcMapFstOptions : public CacheOptions { - // ArcMapFst default caching behaviour is to do no caching. Most mappers are - // cheap and therefore we save memory by not doing caching. - ArcMapFstOptions() : CacheOptions(true, 0) {} - - explicit ArcMapFstOptions(const CacheOptions &opts) : CacheOptions(opts) {} -}; - -template -class ArcMapFst; - -namespace internal { - -// Implementation of delayed ArcMapFst. -template -class ArcMapFstImpl : public CacheImpl { - public: - using Arc = B; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheImpl::EmplaceArc; - using CacheImpl::HasArcs; - using CacheImpl::HasFinal; - using CacheImpl::HasStart; - using CacheImpl::PushArc; - using CacheImpl::SetArcs; - using CacheImpl::SetFinal; - using CacheImpl::SetStart; - - friend class StateIterator>; - - ArcMapFstImpl(const Fst &fst, const C &mapper, - const ArcMapFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - mapper_(new C(mapper)), - own_mapper_(true), - superfinal_(kNoStateId), - nstates_(0) { - Init(); - } - - ArcMapFstImpl(const Fst &fst, C *mapper, const ArcMapFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - mapper_(mapper), - own_mapper_(false), - superfinal_(kNoStateId), - nstates_(0) { - Init(); - } - - ArcMapFstImpl(const ArcMapFstImpl &impl) - : CacheImpl(impl), - fst_(impl.fst_->Copy(true)), - mapper_(new C(*impl.mapper_)), - own_mapper_(true), - superfinal_(kNoStateId), - nstates_(0) { - Init(); - } - - ~ArcMapFstImpl() override { - if (own_mapper_) delete mapper_; - } - - StateId Start() { - if (!HasStart()) SetStart(FindOState(fst_->Start())); - return CacheImpl::Start(); - } - - Weight Final(StateId s) { - if (!HasFinal(s)) { - switch (final_action_) { - case MAP_NO_SUPERFINAL: - default: { - const auto final_arc = - (*mapper_)(A(0, 0, fst_->Final(FindIState(s)), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) { - FSTERROR() << "ArcMapFst: Non-zero arc labels for superfinal arc"; - SetProperties(kError, kError); - } - SetFinal(s, final_arc.weight); - break; - } - case MAP_ALLOW_SUPERFINAL: { - if (s == superfinal_) { - SetFinal(s); - } else { - const auto final_arc = - (*mapper_)(A(0, 0, fst_->Final(FindIState(s)), kNoStateId)); - if (final_arc.ilabel == 0 && final_arc.olabel == 0) { - SetFinal(s, final_arc.weight); - } else { - SetFinal(s, Weight::Zero()); - } - } - break; - } - case MAP_REQUIRE_SUPERFINAL: { - SetFinal(s, s == superfinal_ ? Weight::One() : Weight::Zero()); - break; - } - } - } - return CacheImpl::Final(s); - } - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && (fst_->Properties(kError, false) || - (mapper_->Properties(0) & kError))) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - void Expand(StateId s) { - // Add exiting arcs. - if (s == superfinal_) { - SetArcs(s); - return; - } - for (ArcIterator> aiter(*fst_, FindIState(s)); !aiter.Done(); - aiter.Next()) { - auto aarc = aiter.Value(); - aarc.nextstate = FindOState(aarc.nextstate); - PushArc(s, (*mapper_)(aarc)); - } - - // Check for superfinal arcs. - if (!HasFinal(s) || Final(s) == Weight::Zero()) { - switch (final_action_) { - case MAP_NO_SUPERFINAL: - default: - break; - case MAP_ALLOW_SUPERFINAL: { - auto final_arc = - (*mapper_)(A(0, 0, fst_->Final(FindIState(s)), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) { - if (superfinal_ == kNoStateId) superfinal_ = nstates_++; - final_arc.nextstate = superfinal_; - PushArc(s, std::move(final_arc)); - } - break; - } - case MAP_REQUIRE_SUPERFINAL: { - const auto final_arc = - (*mapper_)(A(0, 0, fst_->Final(FindIState(s)), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0 || - final_arc.weight != B::Weight::Zero()) { - EmplaceArc(s, final_arc.ilabel, final_arc.olabel, final_arc.weight, - superfinal_); - } - break; - } - } - } - SetArcs(s); - } - - private: - void Init() { - SetType("map"); - 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); - } - if (fst_->Start() == kNoStateId) { - final_action_ = MAP_NO_SUPERFINAL; - SetProperties(kNullProperties); - } else { - final_action_ = mapper_->FinalAction(); - uint64_t props = fst_->Properties(kCopyProperties, false); - SetProperties(mapper_->Properties(props)); - if (final_action_ == MAP_REQUIRE_SUPERFINAL) superfinal_ = 0; - } - } - - // Maps from output state to input state. - StateId FindIState(StateId s) { - if (superfinal_ == kNoStateId || s < superfinal_) { - return s; - } else { - return s - 1; - } - } - - // Maps from input state to output state. - StateId FindOState(StateId is) { - auto os = is; - if (!(superfinal_ == kNoStateId || is < superfinal_)) ++os; - if (os >= nstates_) nstates_ = os + 1; - return os; - } - - std::unique_ptr> fst_; - C *mapper_; - const bool own_mapper_; - MapFinalAction final_action_; - StateId superfinal_; - StateId nstates_; -}; - -} // 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 ArcMapFst : public ImplToFst> { - public: - using Arc = B; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - using Impl = internal::ArcMapFstImpl; - - friend class ArcIterator>; - friend class StateIterator>; - - explicit ArcMapFst(const Fst &fst, const C &mapper = C(), - const ArcMapFstOptions &opts = ArcMapFstOptions()) - : ImplToFst(std::make_shared(fst, mapper, opts)) {} - - ArcMapFst(const Fst &fst, C *mapper, - const ArcMapFstOptions &opts = ArcMapFstOptions()) - : ImplToFst(std::make_shared(fst, mapper, opts)) {} - - // See Fst<>::Copy() for doc. - ArcMapFst(const ArcMapFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Get a copy of this ArcMapFst. See Fst<>::Copy() for further doc. - ArcMapFst *Copy(bool safe = false) const override { - return new ArcMapFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - protected: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - private: - ArcMapFst &operator=(const ArcMapFst &) = delete; -}; - -// Specialization for ArcMapFst. -// -// This may be derived from. -template -class StateIterator> : public StateIteratorBase { - public: - using StateId = typename B::StateId; - - explicit StateIterator(const ArcMapFst &fst) - : impl_(fst.GetImpl()), - siter_(*impl_->fst_), - s_(0), - superfinal_(impl_->final_action_ == MAP_REQUIRE_SUPERFINAL) { - CheckSuperfinal(); - } - - bool Done() const final { return siter_.Done() && !superfinal_; } - - StateId Value() const final { return s_; } - - void Next() final { - ++s_; - if (!siter_.Done()) { - siter_.Next(); - CheckSuperfinal(); - } else if (superfinal_) { - superfinal_ = false; - } - } - - void Reset() final { - s_ = 0; - siter_.Reset(); - superfinal_ = impl_->final_action_ == MAP_REQUIRE_SUPERFINAL; - CheckSuperfinal(); - } - - private: - void CheckSuperfinal() { - if (impl_->final_action_ != MAP_ALLOW_SUPERFINAL || superfinal_) return; - if (!siter_.Done()) { - const auto final_arc = - (*impl_->mapper_)(A(0, 0, impl_->fst_->Final(s_), kNoStateId)); - if (final_arc.ilabel != 0 || final_arc.olabel != 0) superfinal_ = true; - } - } - - const internal::ArcMapFstImpl *impl_; - StateIterator> siter_; - StateId s_; - bool superfinal_; // True if there is a superfinal state and not done. -}; - -// Specialization for ArcMapFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename A::StateId; - - ArcIterator(const ArcMapFst &fst, StateId s) - : CacheArcIterator>(fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void ArcMapFst::InitStateIterator( - StateIteratorData *data) const { - data->base = std::make_unique>>(*this); -} - -// CTAD deduction guides -// This allows constructing ArcMapFsts without specifying all the types. -template -ArcMapFst(const Fst &, const ArcMapper &) - -> ArcMapFst; - -// As above, but using the ArcMapFst(..., ArcMapper *) constructor. -template -ArcMapFst(const Fst &, ArcMapper *) - -> ArcMapFst; - -// Utility Mappers. - -// Mapper that returns its input. -template -class IdentityArcMapper { - public: - using FromArc = A; - using ToArc = A; - - constexpr ToArc operator()(const FromArc &arc) const { return arc; } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { return props; } -}; - -// Mapper that converts all input symbols to epsilon. -template -class InputEpsilonMapper { - public: - using FromArc = A; - using ToArc = A; - - constexpr ToArc operator()(const FromArc &arc) const { - return ToArc(0, arc.olabel, arc.weight, arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return (props & kSetArcProperties) | kIEpsilons | kILabelSorted; - } -}; - -// Mapper that converts all output symbols to epsilon. -template -class OutputEpsilonMapper { - public: - using FromArc = A; - using ToArc = A; - - constexpr ToArc operator()(const FromArc &arc) const { - return ToArc(arc.ilabel, 0, arc.weight, arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return (props & kSetArcProperties) | kOEpsilons | kOLabelSorted; - } -}; - -// Mapper that returns its input with final states redirected to a single -// super-final state. -template -class SuperFinalMapper { - public: - using FromArc = A; - using ToArc = A; - using Label = typename FromArc::Label; - using Weight = typename FromArc::Weight; - - // Arg allows setting super-final label. - constexpr explicit SuperFinalMapper(Label final_label = 0) - : final_label_(final_label) {} - - ToArc operator()(const FromArc &arc) const { - // Super-final arc. - if (arc.nextstate == kNoStateId && arc.weight != Weight::Zero()) { - return ToArc(final_label_, final_label_, arc.weight, kNoStateId); - } else { - return arc; - } - } - - constexpr MapFinalAction FinalAction() const { - return MAP_REQUIRE_SUPERFINAL; - } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - uint64_t Properties(uint64_t props) const { - if (final_label_ == 0) { - return props & kAddSuperFinalProperties; - } else { - return props & kAddSuperFinalProperties & kILabelInvariantProperties & - kOLabelInvariantProperties; - } - } - - private: - const Label final_label_; -}; - -// Mapper that leaves labels and nextstate unchanged and constructs a new weight -// from the underlying value of the arc weight. If no weight converter is -// explictly specified, requires that there is a WeightConvert class -// specialization that converts the weights. -template > -class WeightConvertMapper { - public: - using FromArc = A; - using ToArc = B; - using Converter = C; - using FromWeight = typename FromArc::Weight; - using ToWeight = typename ToArc::Weight; - - constexpr explicit WeightConvertMapper(const Converter &c = Converter()) - : convert_weight_(c) {} - - constexpr ToArc operator()(const FromArc &arc) const { - return ToArc(arc.ilabel, arc.olabel, convert_weight_(arc.weight), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { return props; } - - private: - const Converter convert_weight_; -}; - -// Non-precision-changing weight conversions; consider using more efficient -// Cast method instead. - -using StdToLogMapper = WeightConvertMapper; - -using LogToStdMapper = WeightConvertMapper; - -// Precision-changing weight conversions. - -using StdToLog64Mapper = WeightConvertMapper; - -using LogToLog64Mapper = WeightConvertMapper; - -using Log64ToStdMapper = WeightConvertMapper; - -using Log64ToLogMapper = WeightConvertMapper; - -// Mapper from A to GallicArc. -template -class ToGallicMapper { - public: - using FromArc = A; - using ToArc = GallicArc; - - using SW = StringWeight; - using AW = typename FromArc::Weight; - using GW = typename ToArc::Weight; - - ToArc operator()(const FromArc &arc) const { - // Super-final arc. - if (arc.nextstate == kNoStateId && arc.weight != AW::Zero()) { - return ToArc(0, 0, GW(SW::One(), arc.weight), kNoStateId); - // Super-non-final arc. - } else if (arc.nextstate == kNoStateId) { - return ToArc(0, 0, GW::Zero(), kNoStateId); - // Epsilon label. - } else if (arc.olabel == 0) { - return ToArc(arc.ilabel, arc.ilabel, GW(SW::One(), arc.weight), - arc.nextstate); - // Regular label. - } else { - return ToArc(arc.ilabel, arc.ilabel, GW(SW(arc.olabel), arc.weight), - arc.nextstate); - } - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - uint64_t Properties(uint64_t props) const { - return ProjectProperties(props, true) & kWeightInvariantProperties; - } -}; - -// Mapper from GallicArc to A. -template -class FromGallicMapper { - public: - using FromArc = GallicArc; - using ToArc = A; - - using Label = typename ToArc::Label; - using AW = typename ToArc::Weight; - using GW = typename FromArc::Weight; - - explicit FromGallicMapper(Label superfinal_label = 0) - : superfinal_label_(superfinal_label), error_(false) {} - - ToArc operator()(const FromArc &arc) const { - // 'Super-non-final' arc. - if (arc.nextstate == kNoStateId && arc.weight == GW::Zero()) { - return A(arc.ilabel, 0, AW::Zero(), kNoStateId); - } - Label l = kNoLabel; - AW weight = AW::Zero(); - if (!Extract(arc.weight, &weight, &l) || arc.ilabel != arc.olabel) { - FSTERROR() << "FromGallicMapper: Unrepresentable weight: " << arc.weight - << " for arc with ilabel = " << arc.ilabel - << ", olabel = " << arc.olabel - << ", nextstate = " << arc.nextstate; - error_ = true; - } - if (arc.ilabel == 0 && l != 0 && arc.nextstate == kNoStateId) { - return ToArc(superfinal_label_, l, weight, arc.nextstate); - } else { - return ToArc(arc.ilabel, l, weight, arc.nextstate); - } - } - - constexpr MapFinalAction FinalAction() const { return MAP_ALLOW_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - uint64_t Properties(uint64_t inprops) const { - uint64_t outprops = inprops & kOLabelInvariantProperties & - kWeightInvariantProperties & kAddSuperFinalProperties; - if (error_) outprops |= kError; - return outprops; - } - - private: - template - static bool Extract(const GallicWeight &gallic_weight, - typename A::Weight *weight, typename A::Label *label) { - using GW = StringWeight; - const GW &w1 = gallic_weight.Value1(); - const AW &w2 = gallic_weight.Value2(); - typename GW::Iterator iter1(w1); - const Label l = w1.Size() == 1 ? iter1.Value() : 0; - if (l == kStringInfinity || l == kStringBad || w1.Size() > 1) return false; - *label = l; - *weight = w2; - return true; - } - - static bool Extract(const GallicWeight &gallic_weight, - typename A::Weight *weight, typename A::Label *label) { - if (gallic_weight.Size() > 1) return false; - if (gallic_weight.Size() == 0) { - *label = 0; - *weight = A::Weight::Zero(); - return true; - } - return Extract(gallic_weight.Back(), weight, label); - } - - const Label superfinal_label_; - mutable bool error_; -}; - -// Mapper from GallicArc to A. -template -class GallicToNewSymbolsMapper { - public: - using FromArc = GallicArc; - using ToArc = A; - - using Label = typename ToArc::Label; - using StateId = typename ToArc::StateId; - using AW = typename ToArc::Weight; - using GW = typename FromArc::Weight; - using SW = StringWeight; - - explicit GallicToNewSymbolsMapper(MutableFst *fst) - : fst_(fst), - lmax_(0), - osymbols_(fst->OutputSymbols()), - isymbols_(nullptr), - error_(false) { - fst_->DeleteStates(); - state_ = fst_->AddState(); - fst_->SetStart(state_); - fst_->SetFinal(state_); - if (osymbols_) { - std::string name = osymbols_->Name() + "_from_gallic"; - fst_->SetInputSymbols(new SymbolTable(name)); - isymbols_ = fst_->MutableInputSymbols(); - const int64_t zero = 0; - isymbols_->AddSymbol(osymbols_->Find(zero), 0); - } else { - fst_->SetInputSymbols(nullptr); - } - } - - ToArc operator()(const FromArc &arc) { - // Super-non-final arc. - if (arc.nextstate == kNoStateId && arc.weight == GW::Zero()) { - return ToArc(arc.ilabel, 0, AW::Zero(), kNoStateId); - } - SW w1 = arc.weight.Value1(); - AW w2 = arc.weight.Value2(); - Label l; - if (w1.Size() == 0) { - l = 0; - } else if (auto [it, inserted] = map_.emplace(w1, kNoLabel); !inserted) { - l = it->second; - } else { - l = ++lmax_; - it->second = l; - StringWeightIterator iter1(w1); - StateId n; - std::string s; - for (size_t i = 0, p = state_; i < w1.Size(); ++i, iter1.Next(), p = n) { - n = i == w1.Size() - 1 ? state_ : fst_->AddState(); - fst_->AddArc(p, ToArc(i ? 0 : l, iter1.Value(), n)); - if (isymbols_) { - if (i) s = s + "_"; - s = s + osymbols_->Find(iter1.Value()); - } - } - if (isymbols_) isymbols_->AddSymbol(s, l); - } - if (l == kStringInfinity || l == kStringBad || arc.ilabel != arc.olabel) { - FSTERROR() << "GallicToNewSymbolMapper: Unrepresentable weight: " << l; - error_ = true; - } - return ToArc(arc.ilabel, l, w2, arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_ALLOW_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - uint64_t Properties(uint64_t inprops) const { - uint64_t outprops = inprops & kOLabelInvariantProperties & - kWeightInvariantProperties & kAddSuperFinalProperties; - if (error_) outprops |= kError; - return outprops; - } - - private: - class StringKey { - public: - size_t operator()(const SW &x) const { return x.Hash(); } - }; - - using Map = std::unordered_map; - - MutableFst *fst_; - Map map_; - Label lmax_; - StateId state_; - const SymbolTable *osymbols_; - SymbolTable *isymbols_; - mutable bool error_; -}; - -// TODO(kbg): Add common base class for those mappers which do nothing except -// mutate their weights. - -// Mapper to add a constant to all weights. -template -class PlusMapper { - public: - using FromArc = A; - using ToArc = A; - using Weight = typename FromArc::Weight; - - constexpr explicit PlusMapper(Weight weight) : weight_(std::move(weight)) {} - - ToArc operator()(const FromArc &arc) const { - if (arc.weight == Weight::Zero()) return arc; - return ToArc(arc.ilabel, arc.olabel, Plus(arc.weight, weight_), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return props & kWeightInvariantProperties; - } - - private: - const Weight weight_; -}; - -// Mapper to (right) multiply a constant to all weights. -template -class TimesMapper { - public: - using FromArc = A; - using ToArc = A; - using Weight = typename FromArc::Weight; - - constexpr explicit TimesMapper(Weight weight) : weight_(std::move(weight)) {} - - ToArc operator()(const FromArc &arc) const { - if (arc.weight == Weight::Zero()) return arc; - return ToArc(arc.ilabel, arc.olabel, Times(arc.weight, weight_), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return props & kWeightInvariantProperties; - } - - private: - const Weight weight_; -}; - -// Mapper to take all weights to a constant power. The power argument is stored -// as a double, so if there is a floating-point power implementation for this -// weight type, it will take precedence. Otherwise, the power argument's 53 bits -// of integer precision will be implicitly converted to a size_t and the default -// power implementation (iterated multiplication) will be used instead. -template -class PowerMapper { - public: - using FromArc = A; - using ToArc = A; - using Weight = typename FromArc::Weight; - - explicit PowerMapper(double power) : power_(power) {} - - ToArc operator()(const FromArc &arc) const { - return ToArc(arc.ilabel, arc.olabel, Power(arc.weight, power_), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return props & kWeightInvariantProperties; - } - - private: - const double power_; -}; - -// Mapper to reciprocate all non-Zero() weights. -template -class InvertWeightMapper { - public: - using FromArc = A; - using ToArc = A; - using Weight = typename FromArc::Weight; - - ToArc operator()(const FromArc &arc) const { - if (arc.weight == Weight::Zero()) return arc; - return ToArc(arc.ilabel, arc.olabel, Divide(Weight::One(), arc.weight), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return props & kWeightInvariantProperties; - } -}; - -// Mapper to map all non-Zero() weights to One(). -template -class RmWeightMapper { - public: - using FromArc = A; - using ToArc = B; - using FromWeight = typename FromArc::Weight; - using ToWeight = typename ToArc::Weight; - - ToArc operator()(const FromArc &arc) const { - return ToArc( - arc.ilabel, arc.olabel, - arc.weight != FromWeight::Zero() ? ToWeight::One() : ToWeight::Zero(), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return (props & kWeightInvariantProperties) | kUnweighted; - } -}; - -// Mapper to quantize all weights. -template -class QuantizeMapper { - public: - using FromArc = A; - using ToArc = B; - using FromWeight = typename FromArc::Weight; - using ToWeight = typename ToArc::Weight; - - QuantizeMapper() : delta_(kDelta) {} - - explicit QuantizeMapper(float d) : delta_(d) {} - - ToArc operator()(const FromArc &arc) const { - return ToArc(arc.ilabel, arc.olabel, arc.weight.Quantize(delta_), - arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return props & kWeightInvariantProperties; - } - - private: - const float delta_; -}; - -// Mapper from A to B under the assumption: -// -// B::Weight = A::Weight::ReverseWeight -// B::Label == A::Label -// B::StateId == A::StateId -// -// The weight is reversed, while the label and nextstate are preserved. -template -class ReverseWeightMapper { - public: - using FromArc = A; - using ToArc = B; - static_assert(std::is_same_v, - "ToArc::Weight must be FromArc::Weight::ReverseWeight"); - static_assert(std::is_same_v, - "ToArc::Label must be FromArc::Label"); - static_assert( - std::is_same_v, - "ToArc::StateId must be FromArc::StateId"); - - constexpr ToArc operator()(const FromArc &arc) const { - return ToArc(arc.ilabel, arc.olabel, arc.weight.Reverse(), arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_COPY_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { return props; } -}; - -} // namespace fst - -#endif // FST_ARC_MAP_H_ diff --git a/contrib/fstlib/fst/arc.h b/contrib/fstlib/fst/arc.h deleted file mode 100644 index 95a7f04..0000000 --- a/contrib/fstlib/fst/arc.h +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Commonly used FST arc types. - -#ifndef FST_ARC_H_ -#define FST_ARC_H_ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include // For optional argument declarations -#include -#include -#include -#include -#include -#include - -namespace fst { - -template -struct ArcTpl { - public: - using Weight = W; - using Label = L; - using StateId = S; - - Label ilabel; - Label olabel; - Weight weight; - StateId nextstate; - - ArcTpl() noexcept(std::is_nothrow_default_constructible_v) = default; - - template - ArcTpl(Label ilabel, Label olabel, T &&weight, StateId nextstate) - : ilabel(ilabel), - olabel(olabel), - weight(std::forward(weight)), - nextstate(nextstate) {} - - // Arc with weight One. - ArcTpl(Label ilabel, Label olabel, StateId nextstate) - : ArcTpl(ilabel, olabel, Weight::One(), nextstate) {} - - static const std::string &Type() { - static const auto *const type = new std::string( - Weight::Type() == "tropical" ? "standard" : Weight::Type()); - return *type; - } -}; - -using StdArc = ArcTpl; -using LogArc = ArcTpl; -using Log64Arc = ArcTpl; -using RealArc = ArcTpl; -using Real64Arc = ArcTpl; -using SignedLogArc = ArcTpl; -using SignedLog64Arc = ArcTpl; -using ErrorArc = ArcTpl; -using MinMaxArc = ArcTpl; - -// Arc with integer labels and state IDs and string weights. -template -struct StringArc : public ArcTpl> { - public: - using Base = ArcTpl>; - - using Base::Base; - - static const std::string &Type() { - static const auto *const type = new std::string( - S == STRING_LEFT ? "left_standard_string" - : (S == STRING_RIGHT ? "right_standard_string" - : "restricted_standard_string")); - return *type; - } -}; - -// Arc with label and state Id type the same as template arg and with -// weights over the Gallic semiring w.r.t the output labels and weights of A. -template -struct GallicArc : public ArcTpl, - typename A::Label, typename A::StateId> { - using Base = ArcTpl, - typename A::Label, typename A::StateId>; - using Arc = A; - - using Base::Base; - - explicit GallicArc(const Arc &arc) - : Base(arc.ilabel, arc.ilabel, Weight(arc.olabel, arc.weight), - arc.nextstate) {} - - static const std::string &Type() { - static const auto *const type = new std::string( - (G == GALLIC_LEFT - ? "left_gallic_" - : (G == GALLIC_RIGHT - ? "right_gallic_" - : (G == GALLIC_RESTRICT - ? "restricted_gallic_" - : (G == GALLIC_MIN ? "min_gallic_" : "gallic_")))) + - Arc::Type()); - return *type; - } -}; - -// Arc with the reverse of the weight found in its template arg. -template -struct ReverseArc : public ArcTpl { - using Base = ArcTpl; - using Arc = A; - - using Base::Base; - - static const std::string &Type() { - static const auto *const type = new std::string("reverse_" + Arc::Type()); - return *type; - } -}; - -// Arc with integer labels and state IDs and lexicographic weights. -template -using LexicographicArc = ArcTpl>; - -// Arc with integer labels and state IDs and product weights. -template -using ProductArc = ArcTpl>; - -// Arc with label and state ID type the same as first template argument and with -// weights over the n-th Cartesian power of the weight type of the template -// argument. -template -struct PowerArc : public ArcTpl, - typename A::Label, typename A::StateId> { - using Base = ArcTpl, typename A::Label, - typename A::StateId>; - using Arc = A; - - using Base::Base; - - static const std::string &Type() { - static const auto *const type = - new std::string(Arc::Type() + "_^" + std::to_string(n)); - return *type; - } -}; - -// Arc with label and state ID type the same as first template argument and with -// weights over the arbitrary Cartesian power of the weight type. -template -struct SparsePowerArc : public ArcTpl, - typename A::Label, typename A::StateId> { - using Base = ArcTpl, - typename A::Label, typename A::StateId>; - using Arc = A; - - using Base::Base; - - static const std::string &Type() { - static const std::string *const type = [] { - std::string type = Arc::Type() + "_^n"; - if (sizeof(K) != sizeof(uint32_t)) { - type += "_" + std::to_string(CHAR_BIT * sizeof(K)); - } - return new std::string(type); - }(); - return *type; - } -}; - -// Arc with label and state ID type the same as first template argument and with -// expectation weight over the first template argument's weight type and the -// second template argument. -template -struct ExpectationArc : public ArcTpl, - typename A::Label, typename A::StateId> { - using Base = ArcTpl, - typename A::Label, typename A::StateId>; - using Arc = A; - using X1 = typename Arc::Weight; - - using Base::Base; - - static const std::string &Type() { - static const auto *const type = - new std::string("expectation_" + Arc::Type() + "_" + X2::Type()); - return *type; - } -}; - -} // namespace fst - -#endif // FST_ARC_H_ diff --git a/contrib/fstlib/fst/arcfilter.h b/contrib/fstlib/fst/arcfilter.h deleted file mode 100644 index 73a5f4e..0000000 --- a/contrib/fstlib/fst/arcfilter.h +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function objects to restrict which arcs are traversed in an FST. - -#ifndef FST_ARCFILTER_H_ -#define FST_ARCFILTER_H_ - -#include -#include - -namespace fst { - -// True for all arcs. -template -class AnyArcFilter { - public: - bool operator()(const Arc &arc) const { return true; } -}; - -// True for (input/output) epsilon arcs. -template -class EpsilonArcFilter { - public: - bool operator()(const Arc &arc) const { - return arc.ilabel == 0 && arc.olabel == 0; - } -}; - -// True for input epsilon arcs. -template -class InputEpsilonArcFilter { - public: - bool operator()(const Arc &arc) const { return arc.ilabel == 0; } -}; - -// True for output epsilon arcs. -template -class OutputEpsilonArcFilter { - public: - bool operator()(const Arc &arc) const { return arc.olabel == 0; } -}; - -// True if specified label matches (doesn't match) when keep_match is -// true (false). -template -class LabelArcFilter { - public: - using Label = typename Arc::Label; - - explicit LabelArcFilter(Label label, bool match_input = true, - bool keep_match = true) - : label_(label), match_input_(match_input), keep_match_(keep_match) {} - - bool operator()(const Arc &arc) const { - const bool match = (match_input_ ? arc.ilabel : arc.olabel) == label_; - return keep_match_ ? match : !match; - } - - private: - const Label label_; - const bool match_input_; - const bool keep_match_; -}; - -// True if specified labels match (don't match) when keep_match is true (false). -template -class MultiLabelArcFilter { - public: - using Label = typename Arc::Label; - - explicit MultiLabelArcFilter(bool match_input = true, bool keep_match = true) - : match_input_(match_input), keep_match_(keep_match) {} - - bool operator()(const Arc &arc) const { - const Label label = match_input_ ? arc.ilabel : arc.olabel; - const bool match = labels_.Find(label) != labels_.End(); - return keep_match_ ? match : !match; - } - - void AddLabel(Label label) { labels_.Insert(label); } - - private: - CompactSet labels_; - const bool match_input_; - const bool keep_match_; -}; - -} // namespace fst - -#endif // FST_ARCFILTER_H_ diff --git a/contrib/fstlib/fst/arcsort.h b/contrib/fstlib/fst/arcsort.h deleted file mode 100644 index ce75966..0000000 --- a/contrib/fstlib/fst/arcsort.h +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to sort arcs in an FST. - -#ifndef FST_ARCSORT_H_ -#define FST_ARCSORT_H_ - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -template -class ArcSortMapper { - public: - using FromArc = Arc; - using ToArc = Arc; - - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - constexpr ArcSortMapper(const Fst &fst, const Compare &comp) - : fst_(fst), comp_(comp), i_(0) {} - - // Allows updating Fst argument; pass only if changed. - ArcSortMapper(const ArcSortMapper &mapper, - const Fst *fst = nullptr) - : fst_(fst ? *fst : mapper.fst_), comp_(mapper.comp_), i_(0) {} - - StateId Start() { return fst_.Start(); } - - Weight Final(StateId s) const { return fst_.Final(s); } - - void SetState(StateId s) { - i_ = 0; - arcs_.clear(); - arcs_.reserve(fst_.NumArcs(s)); - for (ArcIterator> aiter(fst_, s); !aiter.Done(); aiter.Next()) { - arcs_.push_back(aiter.Value()); - } - std::stable_sort(arcs_.begin(), arcs_.end(), comp_); - } - - bool Done() const { return i_ >= arcs_.size(); } - - const Arc &Value() const { return arcs_[i_]; } - - void Next() { ++i_; } - - MapSymbolsAction InputSymbolsAction() const { return MAP_COPY_SYMBOLS; } - - MapSymbolsAction OutputSymbolsAction() const { return MAP_COPY_SYMBOLS; } - - uint64_t Properties(uint64_t props) const { return comp_.Properties(props); } - - private: - const Fst &fst_; - const Compare &comp_; - std::vector arcs_; - ssize_t i_; // current arc position - - ArcSortMapper &operator=(const ArcSortMapper &) = delete; -}; - -// Sorts the arcs in an FST according to function object 'comp' of type Compare. -// This version modifies its input. Comparison function objects ILabelCompare -// and OLabelCompare are provided by the library. In general, Compare must meet -// the requirements for a comparison function object (e.g., similar to those -// used by std::sort). It must also have a member Properties(uint64_t) that -// specifies the known properties of the sorted FST; it takes as argument the -// input FST's known properties before the sort. -// -// Complexity: -// -// - Time: O(v d log d) -// - Space: O(d) -// -// where v = # of states and d = maximum out-degree. -template -void ArcSort(MutableFst *fst, Compare comp) { - ArcSortMapper mapper(*fst, comp); - StateMap(fst, mapper); -} - -using ArcSortFstOptions = CacheOptions; - -// Sorts the arcs in an FST according to function object 'comp' of type Compare. -// This version is a delayed FST. Comparsion function objects ILabelCompare and -// OLabelCompare are provided by the library. In general, Compare must meet the -// requirements for a comparision function object (e.g., similar to those -// used by std::sort). It must also have a member Properties(uint64_t) that -// specifies the known properties of the sorted FST; it takes as argument the -// input FST's known properties. -// -// Complexity: -// -// - Time: O(v d log d) -// - Space: O(d) -// -// where v = # of states visited, d = maximum out-degree of states visited. -// Constant time and space to visit an input state is assumed and exclusive of -// caching. -template -class ArcSortFst : public StateMapFst> { - using StateMapFst>::GetImpl; - - public: - using StateId = typename Arc::StateId; - using Mapper = ArcSortMapper; - - ArcSortFst(const Fst &fst, const Compare &comp) - : StateMapFst(fst, - ArcSortMapper(fst, comp)) {} - - ArcSortFst(const Fst &fst, const Compare &comp, - const ArcSortFstOptions &opts) - : StateMapFst(fst, Mapper(fst, comp), opts) {} - - // See Fst<>::Copy() for doc. - ArcSortFst(const ArcSortFst &fst, bool safe = false) - : StateMapFst(fst, safe) {} - - // Gets a copy of this ArcSortFst. See Fst<>::Copy() for further doc. - ArcSortFst *Copy(bool safe = false) const override { - return new ArcSortFst(*this, safe); - } - - size_t NumArcs(StateId s) const override { - return GetImpl()->GetFst()->NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) const override { - return GetImpl()->GetFst()->NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) const override { - return GetImpl()->GetFst()->NumOutputEpsilons(s); - } -}; - -// Specialization for ArcSortFst. -template -class StateIterator> - : public StateIterator>> { - public: - explicit StateIterator(const ArcSortFst &fst) - : StateIterator>>(fst) { - } -}; - -// Specialization for ArcSortFst. -template -class ArcIterator> - : public ArcIterator>> { - public: - ArcIterator(const ArcSortFst &fst, typename Arc::StateId s) - : ArcIterator>>(fst, - s) {} -}; - -// Compare class for comparing input labels of arcs. -template -class ILabelCompare { - public: - constexpr ILabelCompare() = default; - - constexpr bool operator()(const Arc &lhs, const Arc &rhs) const { - return std::forward_as_tuple(lhs.ilabel, lhs.olabel) < - std::forward_as_tuple(rhs.ilabel, rhs.olabel); - } - - constexpr uint64_t Properties(uint64_t props) const { - return (props & kArcSortProperties) | kILabelSorted | - (props & kAcceptor ? kOLabelSorted : 0); - } -}; - -// Compare class for comparing output labels of arcs. -template -class OLabelCompare { - public: - constexpr OLabelCompare() = default; - - constexpr bool operator()(const Arc &lhs, const Arc &rhs) const { - return std::forward_as_tuple(lhs.olabel, lhs.ilabel) < - std::forward_as_tuple(rhs.olabel, rhs.ilabel); - } - - constexpr uint64_t Properties(uint64_t props) const { - return (props & kArcSortProperties) | kOLabelSorted | - (props & kAcceptor ? kILabelSorted : 0); - } -}; - -// Useful aliases when using StdArc. - -template -using StdArcSortFst = ArcSortFst; - -using StdILabelCompare = ILabelCompare; - -using StdOLabelCompare = OLabelCompare; - -} // namespace fst - -#endif // FST_ARCSORT_H_ diff --git a/contrib/fstlib/fst/bi-table.h b/contrib/fstlib/fst/bi-table.h deleted file mode 100644 index 46863cf..0000000 --- a/contrib/fstlib/fst/bi-table.h +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes for representing a bijective mapping between an arbitrary entry -// of type T and a signed integral ID. - -#ifndef FST_BI_TABLE_H_ -#define FST_BI_TABLE_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Bitables model bijective mappings between entries of an arbitrary type T and -// an signed integral ID of type I. The IDs are allocated starting from 0 in -// order. -// -// template -// class BiTable { -// public: -// -// // Required constructors. -// BiTable(); -// -// // Looks up integer ID from entry. If it doesn't exist and insert -// / is true, adds it; otherwise, returns -1. -// I FindId(const T &entry, bool insert = true); -// -// // Looks up entry from integer ID. -// const T &FindEntry(I) const; -// -// // Returns number of stored entries. -// I Size() const; -// }; - -// An implementation using a hash map for the entry to ID mapping. H is the -// hash function and E is the equality function. -template , class E = std::equal_to> -class HashBiTable { - public: - // Reserves space for table_size elements. - explicit HashBiTable(size_t table_size = 0, const H &h = H(), - const E &e = E()) - : hash_func_(h), - hash_equal_(e), - entry2id_(table_size, hash_func_, hash_equal_) { - if (table_size) id2entry_.reserve(table_size); - } - - HashBiTable(const HashBiTable &table) - : hash_func_(table.hash_func_), - hash_equal_(table.hash_equal_), - entry2id_(table.entry2id_.begin(), table.entry2id_.end(), - table.entry2id_.size(), hash_func_, hash_equal_), - id2entry_(table.id2entry_) {} - - I FindId(const T &entry, bool insert = true) { - if (!insert) { - const auto it = entry2id_.find(entry); - return it == entry2id_.end() ? -1 : it->second - 1; - } - I &id_ref = entry2id_[entry]; - if (id_ref == 0) { // T not found; stores and assigns a new ID. - id2entry_.push_back(entry); - id_ref = id2entry_.size(); - } - return id_ref - 1; // NB: id_ref = ID + 1. - } - - const T &FindEntry(I s) const { return id2entry_[s]; } - - I Size() const { return id2entry_.size(); } - - // TODO(riley): Add fancy clear-to-size, as in CompactHashBiTable. - void Clear() { - entry2id_.clear(); - id2entry_.clear(); - } - - private: - H hash_func_; - E hash_equal_; - std::unordered_map entry2id_; - std::vector id2entry_; -}; - -// Enables alternative hash set representations below. -enum HSType { HS_STL, HS_FLAT }; - -// Default hash set is STL hash_set. -template -struct HashSet : public std::unordered_set> { - private: - using Base = std::unordered_set>; - public: - using Base::Base; - - void rehash(size_t n) {} -}; - -// An implementation using a hash set for the entry to ID mapping. The hash set -// holds keys which are either the ID or kCurrentKey. These keys can be mapped -// to entries either by looking up in the entry vector or, if kCurrentKey, in -// current_entry_. The hash and key equality functions map to entries first. H -// is the hash function and E is the equality function. -template , class E = std::equal_to, - HSType HS = HS_FLAT> -class CompactHashBiTable { - static_assert(HS == HS_STL || HS == HS_FLAT, "Unsupported hash set type"); - - public: - friend class HashFunc; - friend class HashEqual; - - // Reserves space for table_size elements. - explicit CompactHashBiTable(size_t table_size = 0, const H &h = H(), - const E &e = E()) - : hash_func_(h), - hash_equal_(e), - compact_hash_func_(*this), - compact_hash_equal_(*this), - keys_(table_size, compact_hash_func_, compact_hash_equal_) { - if (table_size) id2entry_.reserve(table_size); - } - - CompactHashBiTable(const CompactHashBiTable &table) - : hash_func_(table.hash_func_), - hash_equal_(table.hash_equal_), - compact_hash_func_(*this), - compact_hash_equal_(*this), - id2entry_(table.id2entry_), - keys_(table.keys_.begin(), table.keys_.end(), table.keys_.size(), - compact_hash_func_, compact_hash_equal_) {} - - I FindId(const T &entry, bool insert = true) { - current_entry_ = entry; - if (insert) { - auto [iter, was_inserted] = keys_.insert(kCurrentKey); - if (!was_inserted) return *iter; // Already exists. - // Overwrites kCurrentKey with a new key value; this is safe because it - // doesn't affect hashing or equality testing. - I key = id2entry_.size(); - const_cast(*iter) = key; - id2entry_.push_back(entry); - return key; - } - const auto it = keys_.find(kCurrentKey); - return it == keys_.end() ? -1 : *it; - } - - const T &FindEntry(I s) const { return id2entry_[s]; } - - I Size() const { return id2entry_.size(); } - - // Clears content; with argument, erases last n IDs. - void Clear(ssize_t n = -1) { - if (n < 0 || n >= id2entry_.size()) { // Clears completely. - keys_.clear(); - id2entry_.clear(); - } else if (n == id2entry_.size() - 1) { // Leaves only key 0. - const T entry = FindEntry(0); - keys_.clear(); - id2entry_.clear(); - FindId(entry, true); - } else { - while (n-- > 0) { - I key = id2entry_.size() - 1; - keys_.erase(key); - id2entry_.pop_back(); - } - keys_.rehash(0); - } - } - - private: - static_assert(std::is_signed_v, "I must be a signed type"); - // ... otherwise >= kCurrentKey comparisons as used below don't work. - // TODO(rybach): (1) don't use >= for key comparison, (2) allow unsigned key - // types. - static constexpr I kCurrentKey = -1; - - class HashFunc { - public: - explicit HashFunc(const CompactHashBiTable &ht) : ht_(&ht) {} - - size_t operator()(I k) const { - if (k >= kCurrentKey) { - return (ht_->hash_func_)(ht_->Key2Entry(k)); - } else { - return 0; - } - } - - private: - const CompactHashBiTable *ht_; - }; - - class HashEqual { - public: - explicit HashEqual(const CompactHashBiTable &ht) : ht_(&ht) {} - - bool operator()(I k1, I k2) const { - if (k1 == k2) { - return true; - } else if (k1 >= kCurrentKey && k2 >= kCurrentKey) { - return (ht_->hash_equal_)(ht_->Key2Entry(k1), ht_->Key2Entry(k2)); - } else { - return false; - } - } - - private: - const CompactHashBiTable *ht_; - }; - - using KeyHashSet = HashSet; - - const T &Key2Entry(I k) const { - if (k == kCurrentKey) { - return current_entry_; - } else { - return id2entry_[k]; - } - } - - H hash_func_; - E hash_equal_; - HashFunc compact_hash_func_; - HashEqual compact_hash_equal_; - std::vector id2entry_; - KeyHashSet keys_; - T current_entry_; -}; - -// An implementation using a vector for the entry to ID mapping. It is passed a -// function object FP that should fingerprint entries uniquely to an integer -// that can used as a vector index. Normally, VectorBiTable constructs the FP -// object. The user can instead pass in this object. -template -class VectorBiTable { - public: - // Reserves table_size cells of space. - explicit VectorBiTable(const FP &fp = FP(), size_t table_size = 0) : fp_(fp) { - if (table_size) id2entry_.reserve(table_size); - } - - VectorBiTable(const VectorBiTable &table) - : fp_(table.fp_), fp2id_(table.fp2id_), id2entry_(table.id2entry_) {} - - I FindId(const T &entry, bool insert = true) { - ssize_t fp = (fp_)(entry); - if (fp >= fp2id_.size()) fp2id_.resize(fp + 1); - I &id_ref = fp2id_[fp]; - if (id_ref == 0) { // T not found. - if (insert) { // Stores and assigns a new ID. - id2entry_.push_back(entry); - id_ref = id2entry_.size(); - } else { - return -1; - } - } - return id_ref - 1; // NB: id_ref = ID + 1. - } - - const T &FindEntry(I s) const { return id2entry_[s]; } - - I Size() const { return id2entry_.size(); } - - const FP &Fingerprint() const { return fp_; } - - private: - FP fp_; - std::vector fp2id_; - std::vector id2entry_; -}; - -// An implementation using a vector and a compact hash table. The selecting -// functor S returns true for entries to be hashed in the vector. The -// fingerprinting functor FP returns a unique fingerprint for each entry to be -// hashed in the vector (these need to be suitable for indexing in a vector). -// The hash functor H is used when hashing entry into the compact hash table. -template , - HSType HS = HS_FLAT> -class VectorHashBiTable { - public: - friend class HashFunc; - friend class HashEqual; - - explicit VectorHashBiTable(const S &s = S(), const FP &fp = FP(), - const H &h = H(), size_t vector_size = 0, - size_t entry_size = 0) - : selector_(s), - fp_(fp), - h_(h), - hash_func_(*this), - hash_equal_(*this), - keys_(0, hash_func_, hash_equal_) { - if (vector_size) fp2id_.reserve(vector_size); - if (entry_size) id2entry_.reserve(entry_size); - } - - VectorHashBiTable(const VectorHashBiTable &table) - : selector_(table.s_), - fp_(table.fp_), - h_(table.h_), - id2entry_(table.id2entry_), - fp2id_(table.fp2id_), - hash_func_(*this), - hash_equal_(*this), - keys_(table.keys_.size(), hash_func_, hash_equal_) { - keys_.insert(table.keys_.begin(), table.keys_.end()); - } - - I FindId(const T &entry, bool insert = true) { - if ((selector_)(entry)) { // Uses the vector if selector_(entry) == true. - uint64_t fp = (fp_)(entry); - if (fp2id_.size() <= fp) fp2id_.resize(fp + 1, 0); - if (fp2id_[fp] == 0) { // T not found. - if (insert) { // Stores and assigns a new ID. - id2entry_.push_back(entry); - fp2id_[fp] = id2entry_.size(); - } else { - return -1; - } - } - return fp2id_[fp] - 1; // NB: assoc_value = ID + 1. - } else { // Uses the hash table otherwise. - current_entry_ = entry; - if (const auto it = keys_.find(kCurrentKey); it != keys_.end()) { - return *it; - } else { - if (insert) { - I key = id2entry_.size(); - id2entry_.push_back(entry); - keys_.insert(key); - return key; - } else { - return -1; - } - } - } - } - - const T &FindEntry(I s) const { return id2entry_[s]; } - - I Size() const { return id2entry_.size(); } - - const S &Selector() const { return selector_; } - - const FP &Fingerprint() const { return fp_; } - - const H &HashFunction() const { return h_; } - - private: - static constexpr I kCurrentKey = -1; - - class HashFunc { - public: - explicit HashFunc(const VectorHashBiTable &ht) : ht_(&ht) {} - - size_t operator()(I k) const { - if (k >= kCurrentKey) { - return (ht_->h_)(ht_->Key2Entry(k)); - } else { - return 0; - } - } - - private: - const VectorHashBiTable *ht_; - }; - - class HashEqual { - public: - explicit HashEqual(const VectorHashBiTable &ht) : ht_(&ht) {} - - bool operator()(I k1, I k2) const { - if (k1 >= kCurrentKey && k2 >= kCurrentKey) { - return ht_->Key2Entry(k1) == ht_->Key2Entry(k2); - } else { - return k1 == k2; - } - } - - private: - const VectorHashBiTable *ht_; - }; - - using KeyHashSet = HashSet; - - const T &Key2Entry(I k) const { - if (k == kCurrentKey) { - return current_entry_; - } else { - return id2entry_[k]; - } - } - - S selector_; // True if entry hashed into vector. - FP fp_; // Fingerprint used for hashing into vector. - H h_; // Hash funcion used for hashing into hash_set. - - std::vector id2entry_; // Maps state IDs to entry. - std::vector fp2id_; // Maps entry fingerprints to IDs. - - // Compact implementation of the hash table mapping entries to state IDs - // using the hash function h_. - HashFunc hash_func_; - HashEqual hash_equal_; - KeyHashSet keys_; - T current_entry_; -}; - -// An implementation using a hash map for the entry to ID mapping. This version -// permits erasing of arbitrary states. The entry T must have == defined and -// its default constructor must produce a entry that will never be seen. F is -// the hash function. -template -class ErasableBiTable { - public: - ErasableBiTable() : first_(0) {} - - I FindId(const T &entry, bool insert = true) { - I &id_ref = entry2id_[entry]; - if (id_ref == 0) { // T not found. - if (insert) { // Stores and assigns a new ID. - id2entry_.push_back(entry); - id_ref = id2entry_.size() + first_; - } else { - return -1; - } - } - return id_ref - 1; // NB: id_ref = ID + 1. - } - - const T &FindEntry(I s) const { return id2entry_[s - first_]; } - - I Size() const { return id2entry_.size(); } - - void Erase(I s) { - auto &ref = id2entry_[s - first_]; - entry2id_.erase(ref); - ref = empty_entry_; - while (!id2entry_.empty() && id2entry_.front() == empty_entry_) { - id2entry_.pop_front(); - ++first_; - } - } - - private: - std::unordered_map entry2id_; - std::deque id2entry_; - const T empty_entry_; - I first_; // I of first element in the deque. -}; - -} // namespace fst - -#endif // FST_BI_TABLE_H_ diff --git a/contrib/fstlib/fst/cache.h b/contrib/fstlib/fst/cache.h deleted file mode 100644 index 4a7c22c..0000000 --- a/contrib/fstlib/fst/cache.h +++ /dev/null @@ -1,1337 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// An FST implementation that caches FST elements of a delayed computation. - -#ifndef FST_CACHE_H_ -#define FST_CACHE_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -DECLARE_bool(fst_default_cache_gc); -DECLARE_int64(fst_default_cache_gc_limit); - -namespace fst { - -// Options for controlling caching behavior; higher level than CacheImplOptions. -struct CacheOptions { - bool gc; // Enables GC. - size_t gc_limit; // Number of bytes allowed before GC. - - explicit CacheOptions( - bool gc = FST_FLAGS_fst_default_cache_gc, - size_t gc_limit = FST_FLAGS_fst_default_cache_gc_limit) - : gc(gc), gc_limit(gc_limit) {} -}; - -// Options for controlling caching behavior, at a lower level than -// CacheOptions; templated on the cache store and allows passing the store. -template -struct CacheImplOptions { - bool gc; // Enables GC. - size_t gc_limit; // Number of bytes allowed before GC. - CacheStore *store; // Cache store. - bool own_store; // Should CacheImpl takes ownership of the store? - - explicit CacheImplOptions( - bool gc = FST_FLAGS_fst_default_cache_gc, - size_t gc_limit = FST_FLAGS_fst_default_cache_gc_limit, - CacheStore *store = nullptr) - : gc(gc), gc_limit(gc_limit), store(store), own_store(true) {} - - explicit CacheImplOptions(const CacheOptions &opts) - : gc(opts.gc), gc_limit(opts.gc_limit), store(nullptr), own_store(true) {} -}; - -// Cache flags. -inline constexpr uint8_t kCacheFinal = 0x01; // Final weight has been cached. -inline constexpr uint8_t kCacheArcs = 0x02; // Arcs have been cached. -inline constexpr uint8_t kCacheInit = 0x04; // Initialized by GC. -inline constexpr uint8_t kCacheRecent = 0x08; // Visited since GC. -inline constexpr uint8_t kCacheFlags = - kCacheFinal | kCacheArcs | kCacheInit | kCacheRecent; - -// Cache state, with arcs stored in a per-state std::vector. -template > -class CacheState { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using ArcAllocator = M; - using StateAllocator = typename std::allocator_traits< - ArcAllocator>::template rebind_alloc>; - - // Provides STL allocator for arcs. - explicit CacheState(const ArcAllocator &alloc) - : final_weight_(Weight::Zero()), - niepsilons_(0), - noepsilons_(0), - arcs_(alloc), - flags_(0), - ref_count_(0) {} - - CacheState(const CacheState &state, const ArcAllocator &alloc) - : final_weight_(state.Final()), - niepsilons_(state.NumInputEpsilons()), - noepsilons_(state.NumOutputEpsilons()), - arcs_(state.arcs_.begin(), state.arcs_.end(), alloc), - flags_(state.Flags()), - ref_count_(0) {} - - void Reset() { - final_weight_ = Weight::Zero(); - niepsilons_ = 0; - noepsilons_ = 0; - ref_count_ = 0; - flags_ = 0; - arcs_.clear(); - } - - Weight Final() const { return final_weight_; } - - size_t NumInputEpsilons() const { return niepsilons_; } - - size_t NumOutputEpsilons() const { return noepsilons_; } - - size_t NumArcs() const { return arcs_.size(); } - - const Arc &GetArc(size_t n) const { return arcs_[n]; } - - // Used by the ArcIterator> efficient implementation. - const Arc *Arcs() const { return !arcs_.empty() ? &arcs_[0] : nullptr; } - - // Accesses flags; used by the caller. - uint8_t Flags() const { return flags_; } - - // Accesses ref count; used by the caller. - int RefCount() const { return ref_count_; } - - void SetFinal(Weight weight = Weight::One()) { - final_weight_ = std::move(weight); - } - - void ReserveArcs(size_t n) { arcs_.reserve(n); } - - // Adds one arc at a time with all needed book-keeping; use PushArc and - // SetArcs for a more efficient alternative. - void AddArc(const Arc &arc) { - IncrementNumEpsilons(arc); - arcs_.push_back(arc); - } - - void AddArc(Arc &&arc) { - IncrementNumEpsilons(arc); - arcs_.push_back(std::move(arc)); - } - - // Adds one arc at a time with delayed book-keeping; finalize with SetArcs(). - void PushArc(const Arc &arc) { arcs_.push_back(arc); } - - void PushArc(Arc &&arc) { arcs_.push_back(std::move(arc)); } - - // Adds one arc at a time with delayed book-keeping; finalize with SetArcs(). - template - void EmplaceArc(T &&...ctor_args) { - arcs_.emplace_back(std::forward(ctor_args)...); - } - - // Finalizes arcs book-keeping; call only once. - void SetArcs() { - for (const auto &arc : arcs_) { - IncrementNumEpsilons(arc); - } - } - - // Modifies nth arc. - void SetArc(const Arc &arc, size_t n) { - if (arcs_[n].ilabel == 0) --niepsilons_; - if (arcs_[n].olabel == 0) --noepsilons_; - IncrementNumEpsilons(arc); - arcs_[n] = arc; - } - - // Deletes all arcs. - void DeleteArcs() { - niepsilons_ = 0; - noepsilons_ = 0; - arcs_.clear(); - } - - void DeleteArcs(size_t n) { - for (size_t i = 0; i < n; ++i) { - if (arcs_.back().ilabel == 0) --niepsilons_; - if (arcs_.back().olabel == 0) --noepsilons_; - arcs_.pop_back(); - } - } - - // Sets status flags; used by the caller. - void SetFlags(uint8_t flags, uint8_t mask) const { - flags_ &= ~mask; - flags_ |= flags; - } - - // Mutates reference counts; used by the caller. - - int IncrRefCount() const { return ++ref_count_; } - - int DecrRefCount() const { return --ref_count_; } - - // Used by the ArcIterator> efficient implementation. - int *MutableRefCount() const { return &ref_count_; } - - // Used for state class allocation. - void *operator new(size_t size, StateAllocator *alloc) { - return alloc->allocate(1); - } - - // For state destruction and memory freeing. - static void Destroy(CacheState *state, StateAllocator *alloc) { - if (state) { - state->~CacheState(); - alloc->deallocate(state, 1); - } - } - - private: - // Update the number of epsilons as a result of having added an arc. - void IncrementNumEpsilons(const Arc &arc) { - if (arc.ilabel == 0) ++niepsilons_; - if (arc.olabel == 0) ++noepsilons_; - } - - Weight final_weight_; // Final weight. - size_t niepsilons_; // # of input epsilons. - size_t noepsilons_; // # of output epsilons. - std::vector arcs_; // Arcs representation. - mutable uint8_t flags_; - mutable int ref_count_; // If 0, available for GC. -}; - -// Cache store, allocating and storing states, providing a mapping from state -// IDs to cached states, and an iterator over these states. The state template -// argument must implement the CacheState interface. The state for a StateId s -// is constructed when requested by GetMutableState(s) if it is not yet stored. -// Initially, a state has a reference count of zero, but the user may increment -// or decrement this to control the time of destruction. In particular, a state -// is destroyed when: -// -// 1. This instance is destroyed, or -// 2. Clear() or Delete() is called, or -// 3. Possibly (implementation-dependently) when: -// - Garbage collection is enabled (as defined by opts.gc), -// - The cache store size exceeds the limits (as defined by opts.gc_limits), -// - The state's reference count is zero, and -// - The state is not the most recently requested state. -// -// template -// class CacheStore { -// public: -// using State = S; -// using Arc = typename State::Arc; -// using StateId = typename Arc::StateId; -// -// // Required constructors/assignment operators. -// explicit CacheStore(const CacheOptions &opts); -// -// // Returns nullptr if state is not stored. -// const State *GetState(StateId s); -// -// // Creates state if state is not stored. -// State *GetMutableState(StateId s); -// -// // Similar to State::AddArc() but updates cache store book-keeping. -// void AddArc(State *state, const Arc &arc); -// -// // Similar to State::SetArcs() but updates cache store book-keeping; call -// // only once. -// void SetArcs(State *state); -// -// // Similar to State::DeleteArcs() but updates cache store book-keeping. -// -// void DeleteArcs(State *state); -// -// void DeleteArcs(State *state, size_t n); -// -// // Deletes all cached states. -// void Clear(); -// -// // Number of cached states. -// StateId CountStates(); -// -// // Iterates over cached states (in an arbitrary order); only needed if -// // opts.gc is true. -// bool Done() const; // End of iteration. -// StateId Value() const; // Current state. -// void Next(); // Advances to next state (when !Done). -// void Reset(); // Returns to initial condition. -// void Delete(); // Deletes current state and advances to next. -// }; - -// Container cache stores. - -// This class uses a vector of pointers to states to store cached states. -template -class VectorCacheStore { - public: - using State = S; - using Arc = typename State::Arc; - using StateId = typename Arc::StateId; - using StateList = std::list>; - - // Required constructors/assignment operators. - explicit VectorCacheStore(const CacheOptions &opts) : cache_gc_(opts.gc) { - Clear(); - Reset(); - } - - VectorCacheStore(const VectorCacheStore &store) - : cache_gc_(store.cache_gc_) { - CopyStates(store); - Reset(); - } - - ~VectorCacheStore() { Clear(); } - - VectorCacheStore &operator=(const VectorCacheStore &store) { - if (this != &store) { - CopyStates(store); - Reset(); - } - return *this; - } - - bool InBounds(StateId s) const { - return s < static_cast(state_vec_.size()); - } - - // Returns nullptr if state is not stored. - const State *GetState(StateId s) const { - return InBounds(s) ? state_vec_[s] : nullptr; - } - - // Creates state if state is not stored. - State *GetMutableState(StateId s) { - State *state = nullptr; - if (InBounds(s)) { - state = state_vec_[s]; - } else { - state_vec_.resize(s + 1, nullptr); - } - if (!state) { - state = new (&state_alloc_) State(arc_alloc_); - state_vec_[s] = state; - if (cache_gc_) state_list_.push_back(s); - } - return state; - } - - // Similar to State::AddArc() but updates cache store book-keeping - void AddArc(State *state, const Arc &arc) { state->AddArc(arc); } - - // Similar to State::SetArcs() but updates cache store book-keeping; call - // only once. - void SetArcs(State *state) { state->SetArcs(); } - - // Deletes all arcs. - void DeleteArcs(State *state) { state->DeleteArcs(); } - - // Deletes some arcs. - void DeleteArcs(State *state, size_t n) { state->DeleteArcs(n); } - - // Deletes all cached states. - void Clear() { - for (State *s : state_vec_) { - State::Destroy(s, &state_alloc_); - } - state_vec_.clear(); - state_list_.clear(); - } - - StateId CountStates() const { - return std::count_if(state_vec_.begin(), state_vec_.end(), - [](const State *s) { return s != nullptr; }); - } - - // Iterates over cached states (in an arbitrary order); only works if GC is - // enabled (o.w. avoiding state_list_ overhead). - bool Done() const { return iter_ == state_list_.end(); } - - StateId Value() const { return *iter_; } - - void Next() { ++iter_; } - - void Reset() { iter_ = state_list_.begin(); } - - // Deletes current state and advances to next. - void Delete() { - State::Destroy(state_vec_[*iter_], &state_alloc_); - state_vec_[*iter_] = nullptr; - state_list_.erase(iter_++); - } - - private: - void CopyStates(const VectorCacheStore &store) { - Clear(); - state_vec_.reserve(store.state_vec_.size()); - for (size_t s = 0; s < store.state_vec_.size(); ++s) { - State *state = nullptr; - const auto *store_state = store.state_vec_[s]; - if (store_state) { - state = new (&state_alloc_) State(*store_state, arc_alloc_); - if (cache_gc_) state_list_.push_back(s); - } - state_vec_.push_back(state); - } - } - - bool cache_gc_; // Supports iteration when true. - std::vector state_vec_; // Vector of states (or null). - StateList state_list_; // List of states. - typename StateList::iterator iter_; // State list iterator. - typename State::StateAllocator state_alloc_; // For state allocation. - typename State::ArcAllocator arc_alloc_; // For arc allocation. -}; - -// This class uses a hash map from state IDs to pointers to cached states. -template -class HashCacheStore { - public: - using State = S; - using Arc = typename State::Arc; - using StateId = typename Arc::StateId; - - using StateMap = - std::unordered_map, - std::equal_to, - PoolAllocator>>; - - // Required constructors/assignment operators. - explicit HashCacheStore(const CacheOptions &opts) { - Clear(); - Reset(); - } - - HashCacheStore(const HashCacheStore &store) { - CopyStates(store); - Reset(); - } - - ~HashCacheStore() { Clear(); } - - HashCacheStore &operator=(const HashCacheStore &store) { - if (this != &store) { - CopyStates(store); - Reset(); - } - return *this; - } - - // Returns nullptr if state is not stored. - const State *GetState(StateId s) const { - const auto it = state_map_.find(s); - return it != state_map_.end() ? it->second : nullptr; - } - - // Creates state if state is not stored. - State *GetMutableState(StateId s) { - auto *&state = state_map_[s]; - if (!state) state = new (&state_alloc_) State(arc_alloc_); - return state; - } - - // Similar to State::AddArc() but updates cache store book-keeping. - void AddArc(State *state, const Arc &arc) { state->AddArc(arc); } - - // Similar to State::SetArcs() but updates internal cache size; call only - // once. - void SetArcs(State *state) { state->SetArcs(); } - - // Deletes all arcs. - void DeleteArcs(State *state) { state->DeleteArcs(); } - - // Deletes some arcs. - void DeleteArcs(State *state, size_t n) { state->DeleteArcs(n); } - - // Deletes all cached states. - void Clear() { - for (auto &[unused_state_id, state_ptr] : state_map_) { - State::Destroy(state_ptr, &state_alloc_); - } - state_map_.clear(); - } - - StateId CountStates() const { return state_map_.size(); } - - // Iterates over cached states (in an arbitrary order). - bool Done() const { return iter_ == state_map_.end(); } - - StateId Value() const { return iter_->first; } - - void Next() { ++iter_; } - - void Reset() { iter_ = state_map_.begin(); } - - // Deletes current state and advances to next. - void Delete() { - State::Destroy(iter_->second, &state_alloc_); - state_map_.erase(iter_++); - } - - private: - void CopyStates(const HashCacheStore &store) { - Clear(); - for (auto &[state_id, state_ptr] : store.state_map_) { - state_map_[state_id] = new (&state_alloc_) State(*state_ptr, arc_alloc_); - } - } - - StateMap state_map_; // Map from state ID to state. - typename StateMap::iterator iter_; // State map iterator. - typename State::StateAllocator state_alloc_; // For state allocation. - typename State::ArcAllocator arc_alloc_; // For arc allocation. -}; - -// Garbage-colllection cache stores. - -// This class implements a simple garbage collection scheme when -// 'opts.gc_limit = 0'. In particular, the first cached state is reused for each -// new state so long as the reference count is zero on the to-be-reused state. -// Otherwise, the full underlying store is used. The caller can increment the -// reference count to inhibit the GC of in-use states (e.g., in an ArcIterator). -// -// The typical use case for this optimization is when a single pass over a -// cached -// FST is performed with only one-state expanded at a time. -template -class FirstCacheStore { - public: - using State = typename CacheStore::State; - using Arc = typename State::Arc; - using StateId = typename Arc::StateId; - - // Required constructors/assignment operators. - explicit FirstCacheStore(const CacheOptions &opts) - : store_(opts), - cache_gc_(opts.gc_limit == 0), // opts.gc ignored historically. - cache_first_state_id_(kNoStateId), - cache_first_state_(nullptr) {} - - FirstCacheStore(const FirstCacheStore &store) - : store_(store.store_), - cache_gc_(store.cache_gc_), - cache_first_state_id_(store.cache_first_state_id_), - cache_first_state_(store.cache_first_state_id_ != kNoStateId - ? store_.GetMutableState(0) - : nullptr) {} - - FirstCacheStore &operator=( - const FirstCacheStore &store) { - if (this != &store) { - store_ = store.store_; - cache_gc_ = store.cache_gc_; - cache_first_state_id_ = store.cache_first_state_id_; - cache_first_state_ = store.cache_first_state_id_ != kNoStateId - ? store_.GetMutableState(0) - : nullptr; - } - return *this; - } - - // Returns nullptr if state is not stored. - const State *GetState(StateId s) const { - // store_ state 0 may hold first cached state; the rest are shifted by 1. - return s == cache_first_state_id_ ? cache_first_state_ - : store_.GetState(s + 1); - } - - // Creates state if state is not stored. - State *GetMutableState(StateId s) { - // store_ state 0 used to hold first cached state; the rest are shifted by - // 1. - if (cache_first_state_id_ == s) { - return cache_first_state_; // Request for first cached state. - } - if (cache_gc_) { - if (cache_first_state_id_ == kNoStateId) { - cache_first_state_id_ = s; // Sets first cached state. - cache_first_state_ = store_.GetMutableState(0); - cache_first_state_->SetFlags(kCacheInit, kCacheInit); - cache_first_state_->ReserveArcs(2 * kAllocSize); - return cache_first_state_; - } else if (cache_first_state_->RefCount() == 0) { - cache_first_state_id_ = s; // Updates first cached state. - cache_first_state_->Reset(); - cache_first_state_->SetFlags(kCacheInit, kCacheInit); - return cache_first_state_; - } else { // Keeps first cached state. - cache_first_state_->SetFlags(0, kCacheInit); // Clears initialized bit. - cache_gc_ = false; // Disables GC. - } - } - auto *state = store_.GetMutableState(s + 1); - return state; - } - - // Similar to State::AddArc() but updates cache store book-keeping. - void AddArc(State *state, const Arc &arc) { store_.AddArc(state, arc); } - - // Similar to State::SetArcs() but updates internal cache size; call only - // once. - void SetArcs(State *state) { store_.SetArcs(state); } - - // Deletes all arcs - void DeleteArcs(State *state) { store_.DeleteArcs(state); } - - // Deletes some arcs - void DeleteArcs(State *state, size_t n) { store_.DeleteArcs(state, n); } - - // Deletes all cached states - void Clear() { - store_.Clear(); - cache_first_state_id_ = kNoStateId; - cache_first_state_ = nullptr; - } - - StateId CountStates() const { return store_.CountStates(); } - - // Iterates over cached states (in an arbitrary order). Only needed if GC is - // enabled. - bool Done() const { return store_.Done(); } - - StateId Value() const { - // store_ state 0 may hold first cached state; rest shifted + 1. - const auto s = store_.Value(); - return s ? s - 1 : cache_first_state_id_; - } - - void Next() { store_.Next(); } - - void Reset() { store_.Reset(); } - - // Deletes current state and advances to next. - void Delete() { - if (Value() == cache_first_state_id_) { - cache_first_state_id_ = kNoStateId; - cache_first_state_ = nullptr; - } - store_.Delete(); - } - - private: - CacheStore store_; // Underlying store. - bool cache_gc_; // GC enabled. - StateId cache_first_state_id_; // First cached state ID. - State *cache_first_state_; // First cached state. -}; - -// This class implements mark-sweep garbage collection on an underlying cache -// store. If GC is enabled, garbage collection of states is performed in a -// rough approximation of LRU order once when 'gc_limit' bytes is reached. The -// caller can increment the reference count to inhibit the GC of in-use state -// (e.g., in an ArcIterator). With GC enabled, the 'gc_limit' parameter allows -// the caller to trade-off time vs. space. -template -class GCCacheStore { - public: - using State = typename CacheStore::State; - using Arc = typename State::Arc; - using StateId = typename Arc::StateId; - - // Required constructors/assignment operators. - explicit GCCacheStore(const CacheOptions &opts) - : store_(opts), - cache_gc_request_(opts.gc), - cache_limit_(opts.gc_limit > kMinCacheLimit ? opts.gc_limit - : kMinCacheLimit), - cache_gc_(false), - cache_size_(0) {} - - // Returns 0 if state is not stored. - const State *GetState(StateId s) const { return store_.GetState(s); } - - // Creates state if state is not stored - State *GetMutableState(StateId s) { - auto *state = store_.GetMutableState(s); - if (cache_gc_request_ && !(state->Flags() & kCacheInit)) { - state->SetFlags(kCacheInit, kCacheInit); - cache_size_ += sizeof(State) + state->NumArcs() * sizeof(Arc); - // GC is enabled once an uninited state (from underlying store) is seen. - cache_gc_ = true; - if (cache_size_ > cache_limit_) GC(state, false); - } - return state; - } - - // Similar to State::AddArc() but updates cache store book-keeping. - void AddArc(State *state, const Arc &arc) { - store_.AddArc(state, arc); - if (cache_gc_ && (state->Flags() & kCacheInit)) { - cache_size_ += sizeof(Arc); - if (cache_size_ > cache_limit_) GC(state, false); - } - } - - // Similar to State::SetArcs() but updates internal cache size; call only - // once. - void SetArcs(State *state) { - store_.SetArcs(state); - if (cache_gc_ && (state->Flags() & kCacheInit)) { - cache_size_ += state->NumArcs() * sizeof(Arc); - if (cache_size_ > cache_limit_) GC(state, false); - } - } - - // Deletes all arcs. - void DeleteArcs(State *state) { - if (cache_gc_ && (state->Flags() & kCacheInit)) { - cache_size_ -= state->NumArcs() * sizeof(Arc); - } - store_.DeleteArcs(state); - } - - // Deletes some arcs. - void DeleteArcs(State *state, size_t n) { - if (cache_gc_ && (state->Flags() & kCacheInit)) { - cache_size_ -= n * sizeof(Arc); - } - store_.DeleteArcs(state, n); - } - - // Deletes all cached states. - void Clear() { - store_.Clear(); - cache_size_ = 0; - } - - StateId CountStates() const { return store_.CountStates(); } - - // Iterates over cached states (in an arbitrary order); only needed if GC is - // enabled. - bool Done() const { return store_.Done(); } - - StateId Value() const { return store_.Value(); } - - void Next() { store_.Next(); } - - void Reset() { store_.Reset(); } - - // Deletes current state and advances to next. - void Delete() { - if (cache_gc_) { - const auto *state = store_.GetState(Value()); - if (state->Flags() & kCacheInit) { - cache_size_ -= sizeof(State) + state->NumArcs() * sizeof(Arc); - } - } - store_.Delete(); - } - - // Removes from the cache store (not referenced-counted and not the current) - // states that have not been accessed since the last GC until at most - // cache_fraction * cache_limit_ bytes are cached. If that fails to free - // enough, attempts to uncaching recently visited states as well. If still - // unable to free enough memory, then widens cache_limit_. - void GC(const State *current, bool free_recent, float cache_fraction = 0.666); - - // Returns the current cache size in bytes or 0 if GC is disabled. - size_t CacheSize() const { return cache_size_; } - - // Returns the cache limit in bytes. - size_t CacheLimit() const { return cache_limit_; } - - private: - static constexpr size_t kMinCacheLimit = 8096; // Minimum cache limit. - - CacheStore store_; // Underlying store. - bool cache_gc_request_; // GC requested but possibly not yet enabled. - size_t cache_limit_; // Number of bytes allowed before GC. - bool cache_gc_; // GC enabled - size_t cache_size_; // Number of bytes cached. -}; - -template -void GCCacheStore::GC(const State *current, bool free_recent, - float cache_fraction) { - if (!cache_gc_) return; - VLOG(2) << "GCCacheStore: Enter GC: object = " - << "(" << this << "), free recently cached = " << free_recent - << ", cache size = " << cache_size_ - << ", cache frac = " << cache_fraction - << ", cache limit = " << cache_limit_ << "\n"; - size_t cache_target = cache_fraction * cache_limit_; - store_.Reset(); - while (!store_.Done()) { - auto *state = store_.GetMutableState(store_.Value()); - if (cache_size_ > cache_target && state->RefCount() == 0 && - (free_recent || !(state->Flags() & kCacheRecent)) && state != current) { - if (state->Flags() & kCacheInit) { - size_t size = sizeof(State) + state->NumArcs() * sizeof(Arc); - if (size < cache_size_) { - cache_size_ -= size; - } - } - store_.Delete(); - } else { - state->SetFlags(0, kCacheRecent); - store_.Next(); - } - } - if (!free_recent && cache_size_ > cache_target) { // Recurses on recent. - GC(current, true, cache_fraction); - } else if (cache_target > 0) { // Widens cache limit. - while (cache_size_ > cache_target) { - cache_limit_ *= 2; - cache_target *= 2; - } - } else if (cache_size_ > 0) { - FSTERROR() << "GCCacheStore:GC: Unable to free all cached states"; - } - VLOG(2) << "GCCacheStore: Exit GC: object = " - << "(" << this << "), free recently cached = " << free_recent - << ", cache size = " << cache_size_ - << ", cache frac = " << cache_fraction - << ", cache limit = " << cache_limit_ << "\n"; -} - -// This class is the default cache state and store used by CacheBaseImpl. -// It uses VectorCacheStore for storage decorated by FirstCacheStore -// and GCCacheStore to do (optional) garbage collection. -template -class DefaultCacheStore - : public GCCacheStore>>> { - public: - explicit DefaultCacheStore(const CacheOptions &opts) - : GCCacheStore>>>(opts) { - } -}; - -namespace internal { - -// This class is used to cache FST elements stored in states of type State -// (see CacheState) with the flags used to indicate what has been cached. Use -// HasStart(), HasFinal(), and HasArcs() to determine if cached and SetStart(), -// SetFinal(), AddArc(), (or PushArc() and SetArcs()) to cache. Note that you -// must set the final weight even if the state is non-final to mark it as -// cached. The state storage method and any garbage collection policy are -// determined by the cache store. If the store is passed in with the options, -// CacheBaseImpl takes ownership. -template > -class CacheBaseImpl : public FstImpl { - public: - using Arc = typename State::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = CacheStore; - - using FstImpl::Type; - using FstImpl::Properties; - - explicit CacheBaseImpl(const CacheOptions &opts = CacheOptions()) - : has_start_(false), - cache_start_(kNoStateId), - nknown_states_(0), - min_unexpanded_state_id_(0), - max_expanded_state_id_(-1), - cache_gc_(opts.gc), - cache_limit_(opts.gc_limit), - cache_store_(new CacheStore(opts)), - new_cache_store_(true), - own_cache_store_(true) {} - - explicit CacheBaseImpl(const CacheImplOptions &opts) - : has_start_(false), - cache_start_(kNoStateId), - nknown_states_(0), - min_unexpanded_state_id_(0), - max_expanded_state_id_(-1), - cache_gc_(opts.gc), - cache_limit_(opts.gc_limit), - cache_store_( - opts.store ? opts.store - : new CacheStore(CacheOptions(opts.gc, opts.gc_limit))), - new_cache_store_(!opts.store), - own_cache_store_(opts.store ? opts.own_store : true) {} - - // Preserve gc parameters. If preserve_cache is true, also preserves - // cache data. - CacheBaseImpl(const CacheBaseImpl &impl, - bool preserve_cache = false) - : FstImpl(), - has_start_(false), - cache_start_(kNoStateId), - nknown_states_(0), - min_unexpanded_state_id_(0), - max_expanded_state_id_(-1), - cache_gc_(impl.cache_gc_), - cache_limit_(impl.cache_limit_), - cache_store_(new CacheStore(CacheOptions(cache_gc_, cache_limit_))), - new_cache_store_(impl.new_cache_store_ || !preserve_cache), - own_cache_store_(true) { - if (preserve_cache) { - *cache_store_ = *impl.cache_store_; - has_start_ = impl.has_start_; - cache_start_ = impl.cache_start_; - nknown_states_ = impl.nknown_states_; - expanded_states_ = impl.expanded_states_; - min_unexpanded_state_id_ = impl.min_unexpanded_state_id_; - max_expanded_state_id_ = impl.max_expanded_state_id_; - } - } - - ~CacheBaseImpl() override { - if (own_cache_store_) delete cache_store_; - } - - void SetStart(StateId s) { - cache_start_ = s; - has_start_ = true; - if (s >= nknown_states_) nknown_states_ = s + 1; - } - - void SetFinal(StateId s, Weight weight = Weight::One()) { - auto *state = cache_store_->GetMutableState(s); - state->SetFinal(std::move(weight)); - static constexpr auto flags = kCacheFinal | kCacheRecent; - state->SetFlags(flags, flags); - } - - // Adds a single arc to a state but delays cache book-keeping. SetArcs must - // be called when all PushArc and EmplaceArc calls at a state are complete. - // Do not mix with calls to AddArc. - void PushArc(StateId s, const Arc &arc) { - auto *state = cache_store_->GetMutableState(s); - state->PushArc(arc); - } - - void PushArc(StateId s, Arc &&arc) { - auto *state = cache_store_->GetMutableState(s); - state->PushArc(std::move(arc)); - } - - // Adds a single arc to a state but delays cache book-keeping. SetArcs must - // be called when all PushArc and EmplaceArc calls at a state are complete. - // Do not mix with calls to AddArc. - template - void EmplaceArc(StateId s, T &&...ctor_args) { - auto *state = cache_store_->GetMutableState(s); - state->EmplaceArc(std::forward(ctor_args)...); - } - - // Marks arcs of a state as cached and does cache book-keeping after all - // calls to PushArc have been completed. Do not mix with calls to AddArc. - void SetArcs(StateId s) { - auto *state = cache_store_->GetMutableState(s); - cache_store_->SetArcs(state); - const auto narcs = state->NumArcs(); - for (size_t a = 0; a < narcs; ++a) { - const auto &arc = state->GetArc(a); - if (arc.nextstate >= nknown_states_) nknown_states_ = arc.nextstate + 1; - } - SetExpandedState(s); - static constexpr auto flags = kCacheArcs | kCacheRecent; - state->SetFlags(flags, flags); - } - - void ReserveArcs(StateId s, size_t n) { - auto *state = cache_store_->GetMutableState(s); - state->ReserveArcs(n); - } - - void DeleteArcs(StateId s) { - auto *state = cache_store_->GetMutableState(s); - cache_store_->DeleteArcs(state); - } - - void DeleteArcs(StateId s, size_t n) { - auto *state = cache_store_->GetMutableState(s); - cache_store_->DeleteArcs(state, n); - } - - void Clear() { - nknown_states_ = 0; - min_unexpanded_state_id_ = 0; - max_expanded_state_id_ = -1; - has_start_ = false; - cache_start_ = kNoStateId; - cache_store_->Clear(); - } - - // Is the start state cached? - bool HasStart() const { - if (!has_start_ && Properties(kError)) has_start_ = true; - return has_start_; - } - - // Is the final weight of the state cached? - bool HasFinal(StateId s) const { - const auto *state = cache_store_->GetState(s); - if (state && state->Flags() & kCacheFinal) { - state->SetFlags(kCacheRecent, kCacheRecent); - return true; - } else { - return false; - } - } - - // Are arcs of the state cached? - bool HasArcs(StateId s) const { - const auto *state = cache_store_->GetState(s); - if (state && state->Flags() & kCacheArcs) { - state->SetFlags(kCacheRecent, kCacheRecent); - return true; - } else { - return false; - } - } - - StateId Start() const { return cache_start_; } - - Weight Final(StateId s) const { - const auto *state = cache_store_->GetState(s); - return state->Final(); - } - - size_t NumArcs(StateId s) const { - const auto *state = cache_store_->GetState(s); - return state->NumArcs(); - } - - size_t NumInputEpsilons(StateId s) const { - const auto *state = cache_store_->GetState(s); - return state->NumInputEpsilons(); - } - - size_t NumOutputEpsilons(StateId s) const { - const auto *state = cache_store_->GetState(s); - return state->NumOutputEpsilons(); - } - - // Provides information needed for generic arc iterator. - void InitArcIterator(StateId s, ArcIteratorData *data) const { - const auto *state = cache_store_->GetState(s); - data->base = nullptr; - data->narcs = state->NumArcs(); - data->arcs = state->Arcs(); - data->ref_count = state->MutableRefCount(); - state->IncrRefCount(); - } - - // Number of known states. - StateId NumKnownStates() const { return nknown_states_; } - - // Updates number of known states, taking into account the passed state ID. - void UpdateNumKnownStates(StateId s) { - if (s >= nknown_states_) nknown_states_ = s + 1; - } - - // Finds the mininum never-expanded state ID. - StateId MinUnexpandedState() const { - while (min_unexpanded_state_id_ <= max_expanded_state_id_ && - ExpandedState(min_unexpanded_state_id_)) { - ++min_unexpanded_state_id_; - } - return min_unexpanded_state_id_; - } - - // Returns maximum ever-expanded state ID. - StateId MaxExpandedState() const { return max_expanded_state_id_; } - - void SetExpandedState(StateId s) { - if (s > max_expanded_state_id_) max_expanded_state_id_ = s; - if (s < min_unexpanded_state_id_) return; - if (s == min_unexpanded_state_id_) ++min_unexpanded_state_id_; - if (cache_gc_ || cache_limit_ == 0) { - if (expanded_states_.size() <= static_cast(s)) - expanded_states_.resize(s + 1, false); - expanded_states_[s] = true; - } - } - - bool ExpandedState(StateId s) const { - if (cache_gc_ || cache_limit_ == 0) { - return expanded_states_[s]; - } else if (new_cache_store_) { - return cache_store_->GetState(s) != nullptr; - } else { - // If the cache was not created by this class, then the cached state needs - // to be inspected to update nknown_states_. - return false; - } - } - - const CacheStore *GetCacheStore() const { return cache_store_; } - - CacheStore *GetCacheStore() { return cache_store_; } - - // Caching on/off switch, limit and size accessors. - - bool GetCacheGc() const { return cache_gc_; } - - size_t GetCacheLimit() const { return cache_limit_; } - - private: - mutable bool has_start_; // Is the start state cached? - StateId cache_start_; // ID of start state. - StateId nknown_states_; // Number of known states. - std::vector expanded_states_; // States that have been expanded. - mutable StateId min_unexpanded_state_id_; // Minimum never-expanded state ID - mutable StateId max_expanded_state_id_; // Maximum ever-expanded state ID - bool cache_gc_; // GC enabled. - size_t cache_limit_; // Number of bytes allowed before GC. - CacheStore *cache_store_; // The store of cached states. - bool new_cache_store_; // Was the store was created by class? - bool own_cache_store_; // Is the store owned by class? - - CacheBaseImpl &operator=(const CacheBaseImpl &impl) = delete; -}; - -// A CacheBaseImpl with the default cache state type. -template -class CacheImpl : public CacheBaseImpl> { - public: - using State = CacheState; - - CacheImpl() = default; - - explicit CacheImpl(const CacheOptions &opts) - : CacheBaseImpl>(opts) {} - - CacheImpl(const CacheImpl &impl, bool preserve_cache = false) - : CacheBaseImpl(impl, preserve_cache) {} - - private: - CacheImpl &operator=(const CacheImpl &impl) = delete; -}; - -} // namespace internal - -// Use this to make a state iterator for a CacheBaseImpl-derived FST, which must -// have Arc and Store types defined. Note this iterator only returns those -// states reachable from the initial state, so consider implementing a -// class-specific one. -// -// This class may be derived from. -template -class CacheStateIterator : public StateIteratorBase { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = typename FST::Store; - using State = typename Store::State; - using Impl = internal::CacheBaseImpl; - - CacheStateIterator(const FST &fst, Impl *impl) - : fst_(fst), impl_(impl), s_(0) { - fst_.Start(); // Forces start state. - } - - bool Done() const final { - if (s_ < impl_->NumKnownStates()) return false; - for (StateId u = impl_->MinUnexpandedState(); u < impl_->NumKnownStates(); - u = impl_->MinUnexpandedState()) { - // Forces state expansion. - ArcIterator aiter(fst_, u); - aiter.SetFlags(kArcValueFlags, kArcValueFlags | kArcNoCache); - for (; !aiter.Done(); aiter.Next()) { - impl_->UpdateNumKnownStates(aiter.Value().nextstate); - } - impl_->SetExpandedState(u); - if (s_ < impl_->NumKnownStates()) return false; - } - return true; - } - - StateId Value() const final { return s_; } - - void Next() final { ++s_; } - - void Reset() final { s_ = 0; } - - private: - const FST &fst_; - Impl *impl_; - StateId s_; -}; - -// Used to make an arc iterator for a CacheBaseImpl-derived FST, which must -// have Arc and State types defined. -template -class CacheArcIterator { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = typename FST::Store; - using State = typename Store::State; - using Impl = internal::CacheBaseImpl; - - CacheArcIterator(Impl *impl, StateId s) : i_(0) { - state_ = impl->GetCacheStore()->GetMutableState(s); - state_->IncrRefCount(); - } - - ~CacheArcIterator() { state_->DecrRefCount(); } - - bool Done() const { return i_ >= state_->NumArcs(); } - - const Arc &Value() const { return state_->GetArc(i_); } - - void Next() { ++i_; } - - size_t Position() const { return i_; } - - void Reset() { i_ = 0; } - - void Seek(size_t a) { i_ = a; } - - constexpr uint8_t Flags() const { return kArcValueFlags; } - - void SetFlags(uint8_t flags, uint8_t mask) {} - - private: - const State *state_; - size_t i_; - - CacheArcIterator(const CacheArcIterator &) = delete; - CacheArcIterator &operator=(const CacheArcIterator &) = delete; -}; - -// Use this to make a mutable arc iterator for a CacheBaseImpl-derived FST, -// which must have types Arc and Store defined. -template -class CacheMutableArcIterator - : public MutableArcIteratorBase { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = typename FST::Store; - using State = typename Store::State; - using Impl = internal::CacheBaseImpl; - - // User must call MutateCheck() in the constructor. - CacheMutableArcIterator(Impl *impl, StateId s) : i_(0), s_(s), impl_(impl) { - state_ = impl_->GetCacheStore()->GetMutableState(s_); - state_->IncrRefCount(); - } - - ~CacheMutableArcIterator() override { state_->DecrRefCount(); } - - bool Done() const final { return i_ >= state_->NumArcs(); } - - const Arc &Value() const final { return state_->GetArc(i_); } - - void Next() final { ++i_; } - - size_t Position() const final { return i_; } - - void Reset() final { i_ = 0; } - - void Seek(size_t a) final { i_ = a; } - - void SetValue(const Arc &arc) final { state_->SetArc(arc, i_); } - - uint8_t Flags() const final { return kArcValueFlags; } - - void SetFlags(uint8_t, uint8_t) final {} - - private: - size_t i_; - StateId s_; - Impl *impl_; - State *state_; - - CacheMutableArcIterator(const CacheMutableArcIterator &) = delete; - CacheMutableArcIterator &operator=(const CacheMutableArcIterator &) = delete; -}; - -// Wrap existing CacheStore implementation to use with ExpanderFst. -template -class ExpanderCacheStore { - public: - using State = typename CacheStore::State; - using Arc = typename CacheStore::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit ExpanderCacheStore(const CacheOptions &opts = CacheOptions()) - : store_(opts) {} - - template - State *FindOrExpand(Expander &expander, StateId s) { - auto *state = store_.GetMutableState(s); - if (state->Flags()) { - state->SetFlags(kCacheRecent, kCacheRecent); - } else { - StateBuilder builder(state); - expander.Expand(s, &builder); - state->SetFlags(kCacheFlags, kCacheFlags); - store_.SetArcs(state); - } - return state; - } - - private: - CacheStore store_; - - struct StateBuilder { - State *state; - - explicit StateBuilder(State *state_) : state(state_) {} - - void AddArc(const Arc &arc) { state->PushArc(arc); } - - void AddArc(Arc &&arc) { state->PushArc(std::move(arc)); } - - void SetFinal(Weight weight = Weight::One()) { - state->SetFinal(std::move(weight)); - } - }; -}; - -} // namespace fst - -#endif // FST_CACHE_H_ diff --git a/contrib/fstlib/fst/cc-visitors.h b/contrib/fstlib/fst/cc-visitors.h deleted file mode 100644 index 67e6130..0000000 --- a/contrib/fstlib/fst/cc-visitors.h +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes to visit connected components of an FST. - -#ifndef FST_CC_VISITORS_H_ -#define FST_CC_VISITORS_H_ - -#include -#include - -#include -#include - -namespace fst { - -// Finds and returns connected components. Use with Visit(). -template -class CcVisitor { - public: - using Weight = typename Arc::Weight; - using StateId = typename Arc::StateId; - - // cc[i]: connected component number for state i. - explicit CcVisitor(std::vector *cc) - : comps_(new UnionFind(0, kNoStateId)), cc_(cc), nstates_(0) {} - - // comps: connected components equiv classes. - explicit CcVisitor(UnionFind *comps) - : comps_(comps), cc_(nullptr), nstates_(0) {} - - ~CcVisitor() { - if (cc_) delete comps_; - } - - void InitVisit(const Fst &fst) {} - - bool InitState(StateId s, StateId root) { - ++nstates_; - if (comps_->FindSet(s) == kNoStateId) comps_->MakeSet(s); - return true; - } - - bool WhiteArc(StateId s, const Arc &arc) { - comps_->MakeSet(arc.nextstate); - comps_->Union(s, arc.nextstate); - return true; - } - - bool GreyArc(StateId s, const Arc &arc) { - comps_->Union(s, arc.nextstate); - return true; - } - - bool BlackArc(StateId s, const Arc &arc) { - comps_->Union(s, arc.nextstate); - return true; - } - - void FinishState(StateId s) {} - - void FinishVisit() { - if (cc_) GetCcVector(cc_); - } - - // Returns number of components. - // cc[i]: connected component number for state i. - int GetCcVector(std::vector *cc) { - cc->clear(); - cc->resize(nstates_, kNoStateId); - StateId ncomp = 0; - for (StateId s = 0; s < nstates_; ++s) { - const auto rep = comps_->FindSet(s); - auto &comp = (*cc)[rep]; - if (comp == kNoStateId) { - comp = ncomp; - ++ncomp; - } - (*cc)[s] = comp; - } - return ncomp; - } - - private: - UnionFind *comps_; // Components. - std::vector *cc_; // State's cc number. - StateId nstates_; // State count. -}; - -// Finds and returns strongly-connected components, accessible and -// coaccessible states and related properties. Uses Tarjan's single -// DFS SCC algorithm (see Aho, et al, "Design and Analysis of Computer -// Algorithms", 189pp). Use with DfsVisit(); -template -class SccVisitor { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - // scc[i]: strongly-connected component number for state i. - // SCC numbers will be in topological order for acyclic input. - // access[i]: accessibility of state i. - // coaccess[i]: coaccessibility of state i. - // Any of above can be NULL. - // props: related property bits (cyclicity, initial cyclicity, - // accessibility, coaccessibility) set/cleared (o.w. unchanged). - SccVisitor(std::vector *scc, std::vector *access, - std::vector *coaccess, uint64_t *props) - : scc_(scc), access_(access), coaccess_(coaccess), props_(props) {} - explicit SccVisitor(uint64_t *props) - : scc_(nullptr), access_(nullptr), coaccess_(nullptr), props_(props) {} - - void InitVisit(const Fst &fst); - - bool InitState(StateId s, StateId root); - - bool TreeArc(StateId s, const Arc &arc) { return true; } - - bool BackArc(StateId s, const Arc &arc) { - const auto t = arc.nextstate; - if (dfnumber_[t] < lowlink_[s]) lowlink_[s] = dfnumber_[t]; - if ((*coaccess_)[t]) (*coaccess_)[s] = true; - *props_ |= kCyclic; - *props_ &= ~kAcyclic; - if (t == start_) { - *props_ |= kInitialCyclic; - *props_ &= ~kInitialAcyclic; - } - return true; - } - - bool ForwardOrCrossArc(StateId s, const Arc &arc) { - const auto t = arc.nextstate; - if (dfnumber_[t] < dfnumber_[s] /* cross edge */ && onstack_[t] && - dfnumber_[t] < lowlink_[s]) { - lowlink_[s] = dfnumber_[t]; - } - if ((*coaccess_)[t]) (*coaccess_)[s] = true; - return true; - } - - // Last argument always ignored, but required by the interface. - void FinishState(StateId state, StateId p, const Arc *); - - void FinishVisit() { - // Numbers SCCs in topological order when acyclic. - if (scc_) { - for (size_t s = 0; s < scc_->size(); ++s) { - (*scc_)[s] = nscc_ - 1 - (*scc_)[s]; - } - } - if (coaccess_internal_) delete coaccess_; - } - - private: - std::vector *scc_; // State's scc number. - std::vector *access_; // State's accessibility. - std::vector *coaccess_; // State's coaccessibility. - uint64_t *props_; - const Fst *fst_; - StateId start_; - StateId nstates_; // State count. - StateId nscc_; // SCC count. - bool coaccess_internal_; - std::vector dfnumber_; // State discovery times. - std::vector - lowlink_; // lowlink[state] == dfnumber[state] => SCC root - std::vector onstack_; // Is a state on the SCC stack? - std::vector scc_stack_; // SCC stack, with random access. -}; - -template -inline void SccVisitor::InitVisit(const Fst &fst) { - if (scc_) scc_->clear(); - if (access_) access_->clear(); - if (coaccess_) { - coaccess_->clear(); - coaccess_internal_ = false; - } else { - coaccess_ = new std::vector; - coaccess_internal_ = true; - } - *props_ |= kAcyclic | kInitialAcyclic | kAccessible | kCoAccessible; - *props_ &= ~(kCyclic | kInitialCyclic | kNotAccessible | kNotCoAccessible); - fst_ = &fst; - start_ = fst.Start(); - nstates_ = 0; - nscc_ = 0; - dfnumber_.clear(); - lowlink_.clear(); - onstack_.clear(); - scc_stack_.clear(); -} - -template -inline bool SccVisitor::InitState(StateId s, StateId root) { - scc_stack_.push_back(s); - if (static_cast(dfnumber_.size()) <= s) { - if (scc_) scc_->resize(s + 1, -1); - if (access_) access_->resize(s + 1, false); - coaccess_->resize(s + 1, false); - dfnumber_.resize(s + 1, -1); - lowlink_.resize(s + 1, -1); - onstack_.resize(s + 1, false); - } - dfnumber_[s] = nstates_; - lowlink_[s] = nstates_; - onstack_[s] = true; - if (root == start_) { - if (access_) (*access_)[s] = true; - } else { - if (access_) (*access_)[s] = false; - *props_ |= kNotAccessible; - *props_ &= ~kAccessible; - } - ++nstates_; - return true; -} - -template -inline void SccVisitor::FinishState(StateId s, StateId p, const Arc *) { - if (fst_->Final(s) != Weight::Zero()) (*coaccess_)[s] = true; - if (dfnumber_[s] == lowlink_[s]) { // Root of new SCC. - bool scc_coaccess = false; - auto i = scc_stack_.size(); - StateId t; - do { - t = scc_stack_[--i]; - if ((*coaccess_)[t]) scc_coaccess = true; - } while (s != t); - do { - t = scc_stack_.back(); - if (scc_) (*scc_)[t] = nscc_; - if (scc_coaccess) (*coaccess_)[t] = true; - onstack_[t] = false; - scc_stack_.pop_back(); - } while (s != t); - if (!scc_coaccess) { - *props_ |= kNotCoAccessible; - *props_ &= ~kCoAccessible; - } - ++nscc_; - } - if (p != kNoStateId) { - if ((*coaccess_)[s]) (*coaccess_)[p] = true; - if (lowlink_[s] < lowlink_[p]) lowlink_[p] = lowlink_[s]; - } -} - -} // namespace fst - -#endif // FST_CC_VISITORS_H_ diff --git a/contrib/fstlib/fst/closure.h b/contrib/fstlib/fst/closure.h deleted file mode 100644 index 5632021..0000000 --- a/contrib/fstlib/fst/closure.h +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to compute the concatenative closure of an FST. - -#ifndef FST_CLOSURE_H_ -#define FST_CLOSURE_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Computes the concatenative closure. This version modifies its -// MutableFst input. If an FST transduces string x to y with weight a, -// then its closure transduces x to y with weight a, xx to yy with -// weight Times(a, a), xxx to yyy with Times(Times(a, a), a), -// etc. If closure_type == CLOSURE_STAR, then the empty string is -// transduced to itself with weight Weight::One() as well. -// -// Complexity: -// -// Time: O(V) -// Space: O(V) -// -// where V is the number of states. -template -void Closure(MutableFst *fst, ClosureType closure_type) { - using Weight = typename Arc::Weight; - const auto props = fst->Properties(kFstProperties, false); - const auto start = fst->Start(); - for (StateIterator> siter(*fst); !siter.Done(); - siter.Next()) { - const auto s = siter.Value(); - const auto weight = fst->Final(s); - if (weight != Weight::Zero()) fst->AddArc(s, Arc(0, 0, weight, start)); - } - if (closure_type == CLOSURE_STAR) { - fst->ReserveStates(fst->NumStates() + 1); - const auto nstart = fst->AddState(); - fst->SetStart(nstart); - fst->SetFinal(nstart); - if (start != kNoStateId) fst->AddArc(nstart, Arc(0, 0, start)); - } - fst->SetProperties(ClosureProperties(props, closure_type == CLOSURE_STAR), - kFstProperties); -} - -// Computes the concatenative closure. This version modifies its -// RationalFst input. -template -void Closure(RationalFst *fst, ClosureType closure_type) { - fst->GetMutableImpl()->AddClosure(closure_type); -} - -struct ClosureFstOptions : RationalFstOptions { - ClosureType type; - - explicit ClosureFstOptions(const RationalFstOptions &opts, - ClosureType type = CLOSURE_STAR) - : RationalFstOptions(opts), type(type) {} - - explicit ClosureFstOptions(ClosureType type = CLOSURE_STAR) : type(type) {} -}; - -// Computes the concatenative closure. This version is a delayed FST. If an FST -// transduces string x to y with weight a, then its closure transduces x to y -// with weight a, xx to yy with weight Times(a, a), xxx to yyy with weight -// Times(Times(a, a), a), etc. If closure_type == CLOSURE_STAR, then the empty -// string is transduced to itself with weight Weight::One() as well. -// -// Complexity: -// -// Time: O(v) -// Space: O(v) -// -// where v is the number of states visited. Constant time and space to visit an -// input state or arc is assumed and exclusive of caching. -template -class ClosureFst : public RationalFst { - public: - using Arc = A; - - ClosureFst(const Fst &fst, ClosureType closure_type) { - GetMutableImpl()->InitClosure(fst, closure_type); - } - - ClosureFst(const Fst &fst, const ClosureFstOptions &opts) - : RationalFst(opts) { - GetMutableImpl()->InitClosure(fst, opts.type); - } - - // See Fst<>::Copy() for doc. - ClosureFst(const ClosureFst &fst, bool safe = false) - : RationalFst(fst, safe) {} - - // Gets a copy of this ClosureFst. See Fst<>::Copy() for further doc. - ClosureFst *Copy(bool safe = false) const override { - return new ClosureFst(*this, safe); - } - - private: - using ImplToFst>::GetImpl; - using ImplToFst>::GetMutableImpl; -}; - -// Specialization for ClosureFst. -template -class StateIterator> : public StateIterator> { - public: - explicit StateIterator(const ClosureFst &fst) - : StateIterator>(fst) {} -}; - -// Specialization for ClosureFst. -template -class ArcIterator> : public ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const ClosureFst &fst, StateId s) - : ArcIterator>(fst, s) {} -}; - -// Useful alias when using StdArc. -using StdClosureFst = ClosureFst; - -} // namespace fst - -#endif // FST_CLOSURE_H_ diff --git a/contrib/fstlib/fst/compact-fst.h b/contrib/fstlib/fst/compact-fst.h deleted file mode 100644 index 15bdeb3..0000000 --- a/contrib/fstlib/fst/compact-fst.h +++ /dev/null @@ -1,1646 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST Class for memory-efficient representation of common types of -// FSTs: linear automata, acceptors, unweighted FSTs, ... - -#ifndef FST_COMPACT_FST_H_ -#define FST_COMPACT_FST_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include // For optional argument declarations -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -struct CompactFstOptions : public CacheOptions { - // The default caching behaviour is to do no caching. Most compactors are - // cheap and therefore we save memory by not doing caching. - CompactFstOptions() : CacheOptions(true, 0) {} - - explicit CompactFstOptions(const CacheOptions &opts) : CacheOptions(opts) {} -}; - -// New (Fst) Compactor interface - used by CompactFst. This interface -// allows complete flexibility in how the compaction is accomplished. -// -// class Compactor { -// public: -// // Constructor from the Fst to be compacted. If compactor is present, -// // only optional state should be copied from it. Examples of this -// // optional state include compression level or ArcCompactors. -// explicit Compactor(const Fst &fst, -// shared_ptr compactor = nullptr); -// // Copy constructor. Must make a thread-safe copy suitable for use by -// // by Fst::Copy(/*safe=*/true). Only thread-unsafe data structures -// // need to be deeply copied. Ideally, this constructor is O(1) and any -// // large structures are thread-safe and shared, while small ones may -// // need to be copied. -// Compactor(const Compactor &compactor); -// // Default constructor (optional, see comment below). -// Compactor(); -// -// // Returns the start state, number of states, and total number of arcs -// // of the compacted Fst -// StateId Start() const; -// StateId NumStates() const; -// size_t NumArcs() const; -// -// // Accessor class for state attributes. -// class State { -// public: -// State(); // Required, corresponds to kNoStateId. -// // This constructor may, of course, also take a const Compactor * -// // for the first argument. It is recommended to use const Compactor * -// // if possible, but this can be Compactor * if necessary. -// State(Compactor *c, StateId s); // Accessor for StateId 's'. -// StateId GetStateId() const; -// Weight Final() const; -// size_t NumArcs() const; -// // Gets the 'i'th arc for the state. Requires i < NumArcs(). -// // Flags are a bitmask of the kArc*Value flags that ArcIterator uses. -// Arc GetArc(size_t i, uint8_t flags) const; -// }; -// -// // Modifies 'state' accessor to provide access to state id 's'. -// void SetState(StateId s, State *state); -// -// // Tests whether 'fst' can be compacted by this compactor. -// template -// bool IsCompatible(const Fst &fst) const; -// -// // Returns the properties that are always when an FST with the -// // specified properties is compacted using this compactor. -// // This function should clear bits for properties that no longer -// // hold and set those for properties that are known to hold. -// uint64_t Properties(uint64_t props) const; -// -// // Returns a string identifying the type of compactor. -// static const std::string &Type(); -// -// // Returns true if an error has occurred. -// bool Error() const; -// -// // Writes a compactor to a file. -// bool Write(std::ostream &strm, const FstWriteOptions &opts) const; -// -// // Reads a compactor from a file. -// static Compactor *Read(std::istream &strm, const FstReadOptions &opts, -// const FstHeader &hdr); -// }; -// - -// Old ArcCompactor Interface: -// -// This interface is not deprecated; it, along with CompactArcStore and -// other Stores that implement its interface, is simply more constrained -// by essentially forcing the implementation to use an index array -// and an arc array, but giving flexibility in how those are implemented. -// This interface may still be useful and more convenient if that is the -// desired representation. -// -// The ArcCompactor class determines how arcs and final weights are compacted -// and expanded. -// -// Final weights are treated as transitions to the superfinal state, i.e., -// ilabel = olabel = kNoLabel and nextstate = kNoStateId. -// -// There are two types of compactors: -// -// * Fixed out-degree compactors: 'compactor.Size()' returns a positive integer -// 's'. An FST can be compacted by this compactor only if each state has -// exactly 's' outgoing transitions (counting a non-Zero() final weight as a -// transition). A typical example is a compactor for string FSTs, i.e., -// 's == 1'. -// -// * Variable out-degree compactors: 'compactor.Size() == -1'. There are no -// out-degree restrictions for these compactors. -// -// Interface: -// -// class ArcCompactor { -// public: -// // Default constructor (optional, see comment below). -// ArcCompactor(); -// -// // Copy constructor. Must make a thread-safe copy suitable for use by -// // by Fst::Copy(/*safe=*/true). Only thread-unsafe data structures -// // need to be deeply copied. -// ArcCompactor(const ArcCompactor &); -// -// // Element is the type of the compacted transitions. -// using Element = ... -// -// // Returns the compacted representation of a transition 'arc' -// // at a state 's'. -// Element Compact(StateId s, const Arc &arc); -// -// // Returns the transition at state 's' represented by the compacted -// // transition 'e'. -// Arc Expand(StateId s, const Element &e) const; -// -// // Returns -1 for variable out-degree compactors, and the mandatory -// // out-degree otherwise. -// ssize_t Size() const; -// -// // Tests whether an FST can be compacted by this compactor. -// bool Compatible(const Fst &fst) const; -// -// // Returns the properties that are always true for an FST compacted using -// // this compactor. Any Fst with the inverse of these properties should -// // be incompatible. -// uint64_t Properties() const; -// -// // Returns a string identifying the type of compactor. -// static const std::string &Type(); -// -// // Writes a compactor to a file. -// bool Write(std::ostream &strm) const; -// -// // Reads a compactor from a file. -// static ArcCompactor *Read(std::istream &strm); -// }; -// -// The default constructor is only required for FST_REGISTER to work (i.e., -// enabling Convert() and the command-line utilities to work with this new -// compactor). However, a default constructor always needs to be specified for -// this code to compile, but one can have it simply raise an error when called, -// like so: -// -// Compactor::Compactor() { -// FSTERROR() << "Compactor: No default constructor"; -// } - -// Default implementation data for CompactArcCompactor. Only old-style -// ArcCompactors are supported because the CompactArcStore constructors -// use the old API. -// -// DefaultCompact store is thread-compatible, but not thread-safe. -// The copy constructor makes a thread-safe copy. -// -// The implementation contains two arrays: 'states_' and 'compacts_'. -// -// For fixed out-degree compactors, the 'states_' array is unallocated. The -// 'compacts_' array contains the compacted transitions. Its size is -// 'ncompacts_'. The outgoing transitions at a given state are stored -// consecutively. For a given state 's', its 'compactor.Size()' outgoing -// transitions (including a superfinal transition when 's' is final), are stored -// in positions ['s*compactor.Size()', '(s+1)*compactor.Size()'). -// -// For variable out-degree compactors, the states_ array has size -// 'nstates_ + 1' and contains positions in the 'compacts_' array. For a -// given state 's', the compacted transitions of 's' are stored in positions -// ['states_[s]', 'states_[s + 1]') in 'compacts_'. By convention, -// 'states_[nstates_] == ncompacts_'. -// -// In both cases, the superfinal transitions (when 's' is final, i.e., -// 'Final(s) != Weight::Zero()') are stored first. -// -// The unsigned type U is used to represent indices into the compacts_ array. -template -class CompactArcStore { - public: - CompactArcStore() = default; - - // Makes a thread-safe copy. O(1). - CompactArcStore(const CompactArcStore &) = default; - - template - CompactArcStore(const Fst &fst, const ArcCompactor &arc_compactor); - - template - CompactArcStore(const Iterator begin, const Iterator end, - const ArcCompactor &arc_compactor); - - ~CompactArcStore() = default; - - template - static CompactArcStore *Read(std::istream &strm, const FstReadOptions &opts, - const FstHeader &hdr, - const ArcCompactor &arc_compactor); - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const; - - // Returns the starting index in 'compacts_' of the transitions - // for state 'i'. See class-level comment for further details. - // Requires that the CompactArcStore was constructed with a - // variable out-degree compactor. Requires 0 <= i <= NumStates(). - // By convention, States(NumStates()) == NumCompacts(). - Unsigned States(ssize_t i) const { return states_[i]; } - - // Returns the compacted Element at position i. See class-level comment - // for further details. Requires 0 <= i < NumCompacts(). - const Element &Compacts(size_t i) const { return compacts_[i]; } - - size_t NumStates() const { return nstates_; } - - size_t NumCompacts() const { return ncompacts_; } - - size_t NumArcs() const { return narcs_; } - - ssize_t Start() const { return start_; } - - bool Error() const { return error_; } - - // Returns a string identifying the type of data storage container. - static const std::string &Type(); - - private: - std::shared_ptr states_region_; - std::shared_ptr compacts_region_; - // Unowned pointer into states_region_. - Unsigned *states_ = nullptr; - // Unowned pointer into compacts_region_. - Element *compacts_ = nullptr; - size_t nstates_ = 0; - size_t ncompacts_ = 0; - size_t narcs_ = 0; - ssize_t start_ = kNoStateId; - bool error_ = false; -}; - -template -template -CompactArcStore::CompactArcStore( - const Fst &fst, const ArcCompactor &arc_compactor) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - start_ = fst.Start(); - // Counts # of states and arcs. - StateId nfinals = 0; - for (StateIterator> siter(fst); !siter.Done(); siter.Next()) { - ++nstates_; - const auto s = siter.Value(); - narcs_ += fst.NumArcs(s); - if (fst.Final(s) != Weight::Zero()) ++nfinals; - } - if (arc_compactor.Size() == -1) { - states_region_ = fst::WrapUnique(MappedFile::Allocate( - sizeof(states_[0]) * (nstates_ + 1), alignof(decltype(states_[0])))); - states_ = static_cast(states_region_->mutable_data()); - ncompacts_ = narcs_ + nfinals; - compacts_region_ = fst::WrapUnique(MappedFile::Allocate( - sizeof(compacts_[0]) * ncompacts_, alignof(decltype(compacts_[0])))); - compacts_ = static_cast(compacts_region_->mutable_data()); - states_[nstates_] = ncompacts_; - } else { - states_ = nullptr; - ncompacts_ = nstates_ * arc_compactor.Size(); - if ((narcs_ + nfinals) != ncompacts_) { - FSTERROR() << "CompactArcStore: ArcCompactor incompatible with FST"; - error_ = true; - return; - } - compacts_region_ = fst::WrapUnique(MappedFile::Allocate( - sizeof(compacts_[0]) * ncompacts_, alignof(decltype(compacts_[0])))); - compacts_ = static_cast(compacts_region_->mutable_data()); - } - size_t pos = 0; - size_t fpos = 0; - for (size_t s = 0; s < nstates_; ++s) { - fpos = pos; - if (arc_compactor.Size() == -1) states_[s] = pos; - if (fst.Final(s) != Weight::Zero()) { - compacts_[pos++] = arc_compactor.Compact( - s, Arc(kNoLabel, kNoLabel, fst.Final(s), kNoStateId)); - } - for (ArcIterator> aiter(fst, s); !aiter.Done(); aiter.Next()) { - compacts_[pos++] = arc_compactor.Compact(s, aiter.Value()); - } - if ((arc_compactor.Size() != -1) && (pos != fpos + arc_compactor.Size())) { - FSTERROR() << "CompactArcStore: ArcCompactor incompatible with FST"; - error_ = true; - return; - } - } - if (pos != ncompacts_) { - FSTERROR() << "CompactArcStore: ArcCompactor incompatible with FST"; - error_ = true; - return; - } -} - -template -template -CompactArcStore::CompactArcStore( - const Iterator begin, const Iterator end, - const ArcCompactor &arc_compactor) { - using Arc = typename ArcCompactor::Arc; - using Weight = typename Arc::Weight; - if (arc_compactor.Size() != -1) { - ncompacts_ = std::distance(begin, end); - if (arc_compactor.Size() == 1) { - // For strings, allows implicit final weight. Empty input is the empty - // string. - if (ncompacts_ == 0) { - ++ncompacts_; - } else { - const auto arc = - arc_compactor.Expand(ncompacts_ - 1, *(begin + (ncompacts_ - 1))); - if (arc.ilabel != kNoLabel) ++ncompacts_; - } - } - if (ncompacts_ % arc_compactor.Size()) { - FSTERROR() << "CompactArcStore: Size of input container incompatible" - << " with arc compactor"; - error_ = true; - return; - } - if (ncompacts_ == 0) return; - start_ = 0; - nstates_ = ncompacts_ / arc_compactor.Size(); - compacts_region_ = fst::WrapUnique(MappedFile::Allocate( - sizeof(compacts_[0]) * ncompacts_, alignof(decltype(compacts_[0])))); - compacts_ = static_cast(compacts_region_->mutable_data()); - size_t i = 0; - Iterator it = begin; - for (; it != end; ++it, ++i) { - compacts_[i] = *it; - if (arc_compactor.Expand(i, *it).ilabel != kNoLabel) ++narcs_; - } - if (i < ncompacts_) { - compacts_[i] = arc_compactor.Compact( - i, Arc(kNoLabel, kNoLabel, Weight::One(), kNoStateId)); - } - } else { - if (std::distance(begin, end) == 0) return; - // Count # of states, arcs and compacts. - auto it = begin; - for (size_t i = 0; it != end; ++it, ++i) { - const auto arc = arc_compactor.Expand(i, *it); - if (arc.ilabel != kNoLabel) { - ++narcs_; - ++ncompacts_; - } else { - ++nstates_; - if (arc.weight != Weight::Zero()) ++ncompacts_; - } - } - start_ = 0; - compacts_region_ = fst::WrapUnique(MappedFile::Allocate( - sizeof(compacts_[0]) * ncompacts_, alignof(decltype(compacts_[0])))); - compacts_ = static_cast(compacts_region_->mutable_data()); - states_region_ = fst::WrapUnique(MappedFile::Allocate( - sizeof(states_[0]) * (nstates_ + 1), alignof(decltype(states_[0])))); - states_ = static_cast(states_region_->mutable_data()); - states_[nstates_] = ncompacts_; - size_t i = 0; - size_t s = 0; - for (it = begin; it != end; ++it) { - const auto arc = arc_compactor.Expand(i, *it); - if (arc.ilabel != kNoLabel) { - compacts_[i++] = *it; - } else { - states_[s++] = i; - if (arc.weight != Weight::Zero()) compacts_[i++] = *it; - } - } - if ((s != nstates_) || (i != ncompacts_)) { - FSTERROR() << "CompactArcStore: Ill-formed input container"; - error_ = true; - return; - } - } -} - -template -template -CompactArcStore *CompactArcStore::Read( - std::istream &strm, const FstReadOptions &opts, const FstHeader &hdr, - const ArcCompactor &arc_compactor) { - auto data = std::make_unique(); - data->start_ = hdr.Start(); - data->nstates_ = hdr.NumStates(); - data->narcs_ = hdr.NumArcs(); - if (arc_compactor.Size() == -1) { - if ((hdr.GetFlags() & FstHeader::IS_ALIGNED) && !AlignInput(strm)) { - LOG(ERROR) << "CompactArcStore::Read: Alignment failed: " << opts.source; - return nullptr; - } - auto b = (data->nstates_ + 1) * sizeof(Unsigned); - data->states_region_.reset(MappedFile::Map( - strm, opts.mode == FstReadOptions::MAP, opts.source, b)); - if (!strm || !data->states_region_) { - LOG(ERROR) << "CompactArcStore::Read: Read failed: " << opts.source; - return nullptr; - } - data->states_ = - static_cast(data->states_region_->mutable_data()); - } else { - data->states_ = nullptr; - } - data->ncompacts_ = arc_compactor.Size() == -1 - ? data->states_[data->nstates_] - : data->nstates_ * arc_compactor.Size(); - if ((hdr.GetFlags() & FstHeader::IS_ALIGNED) && !AlignInput(strm)) { - LOG(ERROR) << "CompactArcStore::Read: Alignment failed: " << opts.source; - return nullptr; - } - size_t b = data->ncompacts_ * sizeof(Element); - data->compacts_region_.reset( - MappedFile::Map(strm, opts.mode == FstReadOptions::MAP, opts.source, b)); - if (!strm || !data->compacts_region_) { - LOG(ERROR) << "CompactArcStore::Read: Read failed: " << opts.source; - return nullptr; - } - data->compacts_ = - static_cast(data->compacts_region_->mutable_data()); - return data.release(); -} - -template -bool CompactArcStore::Write( - std::ostream &strm, const FstWriteOptions &opts) const { - if (states_) { - if (opts.align && !AlignOutput(strm)) { - LOG(ERROR) << "CompactArcStore::Write: Alignment failed: " << opts.source; - return false; - } - strm.write(reinterpret_cast(states_), - (nstates_ + 1) * sizeof(Unsigned)); - } - if (opts.align && !AlignOutput(strm)) { - LOG(ERROR) << "CompactArcStore::Write: Alignment failed: " << opts.source; - return false; - } - strm.write(reinterpret_cast(compacts_), - ncompacts_ * sizeof(Element)); - strm.flush(); - if (!strm) { - LOG(ERROR) << "CompactArcStore::Write: Write failed: " << opts.source; - return false; - } - return true; -} - -template -const std::string &CompactArcStore::Type() { - static const std::string *const type = new std::string("compact"); - return *type; -} - -template -class CompactArcState; - -// Wraps an old-style arc compactor and a compact store as a new Fst compactor. -// The copy constructors of AC and S must make thread-safe copies and should -// be O(1). -template */> -class CompactArcCompactor { - public: - using ArcCompactor = AC; - using Unsigned = U; - using CompactStore = S; - using Element = typename AC::Element; - using Arc = typename AC::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - using State = CompactArcState; - friend State; - - CompactArcCompactor() : arc_compactor_(nullptr), compact_store_(nullptr) {} - - // Constructs from Fst. - explicit CompactArcCompactor(const Fst &fst, - ArcCompactor &&arc_compactor = ArcCompactor()) - : CompactArcCompactor( - fst, std::make_shared(std::move(arc_compactor))) {} - - CompactArcCompactor(const Fst &fst, - std::shared_ptr arc_compactor) - : arc_compactor_(std::move(arc_compactor)), - compact_store_(std::make_shared(fst, *arc_compactor_)) {} - - CompactArcCompactor(const Fst &fst, - std::shared_ptr compactor) - : arc_compactor_(compactor->arc_compactor_), - compact_store_(compactor->compact_store_ == nullptr - ? std::make_shared(fst, *arc_compactor_) - : compactor->compact_store_) {} - - // Constructs from CompactStore. - CompactArcCompactor(std::shared_ptr arc_compactor, - std::shared_ptr compact_store) - : arc_compactor_(std::move(arc_compactor)), - compact_store_(std::move(compact_store)) {} - - // The following 2 constructors take as input two iterators delimiting a set - // of (already) compacted transitions, starting with the transitions out of - // the initial state. The format of the input differs for fixed out-degree - // and variable out-degree arc compactors. - // - // - For fixed out-degree arc compactors, the final weight (encoded as a - // compacted transition) needs to be given only for final states. All strings - // (arc compactor of size 1) will be assume to be terminated by a final state - // even when the final state is not implicitely given. - // - // - For variable out-degree arc compactors, the final weight (encoded as a - // compacted transition) needs to be given for all states and must appeared - // first in the list (for state s, final weight of s, followed by outgoing - // transitons in s). - // - // These 2 constructors allows the direct construction of a CompactArcFst - // without first creating a more memory-hungry regular FST. This is useful - // when memory usage is severely constrained. - // - // Usage: - // CompactArcFst<...> fst( - // std::make_shared::Compactor>(b, e)); - template - CompactArcCompactor(const Iterator b, const Iterator e, - std::shared_ptr arc_compactor) - : arc_compactor_(std::move(arc_compactor)), - compact_store_(std::make_shared(b, e, *arc_compactor_)) {} - - template - CompactArcCompactor(const Iterator b, const Iterator e) - : CompactArcCompactor(b, e, std::make_shared()) {} - - // Copy constructor. This makes a thread-safe copy, so requires that - // The ArcCompactor and CompactStore copy constructors make thread-safe - // copies. - CompactArcCompactor(const CompactArcCompactor &compactor) - : arc_compactor_( - compactor.GetArcCompactor() == nullptr - ? nullptr - : std::make_shared(*compactor.GetArcCompactor())), - compact_store_(compactor.GetCompactStore() == nullptr - ? nullptr - : std::make_shared( - *compactor.GetCompactStore())) {} - - template - explicit CompactArcCompactor( - const CompactArcCompactor &compactor) - : arc_compactor_( - compactor.GetArcCompactor() == nullptr - ? nullptr - : std::make_shared(*compactor.GetArcCompactor())), - compact_store_(compactor.GetCompactStore() == nullptr - ? nullptr - : std::make_shared( - *compactor.GetCompactStore())) {} - - StateId Start() const { return compact_store_->Start(); } - StateId NumStates() const { return compact_store_->NumStates(); } - size_t NumArcs() const { return compact_store_->NumArcs(); } - - void SetState(StateId s, State *state) const { - if (state->GetStateId() != s) state->Set(this, s); - } - - static CompactArcCompactor *Read(std::istream &strm, - const FstReadOptions &opts, - const FstHeader &hdr) { - std::shared_ptr arc_compactor(ArcCompactor::Read(strm)); - if (arc_compactor == nullptr) return nullptr; - std::shared_ptr compact_store(S::Read(strm, opts, hdr, *arc_compactor)); - if (compact_store == nullptr) return nullptr; - return new CompactArcCompactor(arc_compactor, compact_store); - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const { - return arc_compactor_->Write(strm) && compact_store_->Write(strm, opts); - } - - uint64_t Properties(uint64_t props) const { - // ArcCompactor properties can just be or-ed in since it is assumed that - // if the ArcCompactor sets a property, any FST with the inverse - // property is incompatible. - return arc_compactor_->Properties() | props; - } - - bool IsCompatible(const Fst &fst) const { - return arc_compactor_->Compatible(fst); - } - - bool Error() const { return compact_store_->Error(); } - - bool HasFixedOutdegree() const { return arc_compactor_->Size() != -1; } - - static const std::string &Type() { - static const std::string *const type = [] { - std::string type = "compact"; - if (sizeof(U) != sizeof(uint32_t)) type += std::to_string(8 * sizeof(U)); - type += "_"; - type += ArcCompactor::Type(); - if (CompactStore::Type() != "compact") { - type += "_"; - type += CompactStore::Type(); - } - return new std::string(type); - }(); - return *type; - } - - const ArcCompactor *GetArcCompactor() const { return arc_compactor_.get(); } - const CompactStore *GetCompactStore() const { return compact_store_.get(); } - - ArcCompactor *MutableArcCompactor() { return arc_compactor_.get(); } - CompactStore *MutableCompactStore() { return compact_store_.get(); } - - std::shared_ptr SharedArcCompactor() { return arc_compactor_; } - std::shared_ptr SharedCompactStore() { return compact_store_; } - - // TODO(allauzen): remove dependencies on this method and make private. - Arc ComputeArc(StateId s, Unsigned i, uint8_t flags) const { - return arc_compactor_->Expand(s, compact_store_->Compacts(i), flags); - } - - private: - std::pair CompactsRange(StateId s) const { - std::pair range; - if (HasFixedOutdegree()) { - range.first = s * arc_compactor_->Size(); - range.second = arc_compactor_->Size(); - } else { - range.first = compact_store_->States(s); - range.second = compact_store_->States(s + 1) - range.first; - } - return range; - } - - private: - std::shared_ptr arc_compactor_; - std::shared_ptr compact_store_; -}; - -// Default implementation of state attributes accessor class for -// CompactArcCompactor. Use of efficient specialization strongly encouraged. -template -class CompactArcState { - public: - using Arc = typename ArcCompactor::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - using Compactor = CompactArcCompactor; - - CompactArcState() = default; - - CompactArcState(const Compactor *compactor, StateId s) - : compactor_(compactor), - s_(s), - range_(compactor->CompactsRange(s)), - has_final_( - range_.second != 0 && - compactor->ComputeArc(s, range_.first, kArcILabelValue).ilabel == - kNoLabel) { - if (has_final_) { - ++range_.first; - --range_.second; - } - } - - void Set(const Compactor *compactor, StateId s) { - compactor_ = compactor; - s_ = s; - range_ = compactor->CompactsRange(s); - if (range_.second != 0 && - compactor->ComputeArc(s, range_.first, kArcILabelValue).ilabel == - kNoLabel) { - has_final_ = true; - ++range_.first; - --range_.second; - } else { - has_final_ = false; - } - } - - StateId GetStateId() const { return s_; } - - Weight Final() const { - if (!has_final_) return Weight::Zero(); - return compactor_->ComputeArc(s_, range_.first - 1, kArcWeightValue).weight; - } - - size_t NumArcs() const { return range_.second; } - - Arc GetArc(size_t i, uint8_t flags) const { - return compactor_->ComputeArc(s_, range_.first + i, flags); - } - - private: - const Compactor *compactor_ = nullptr; // borrowed ref. - StateId s_ = kNoStateId; - std::pair range_ = {0, 0}; - bool has_final_ = false; -}; - -// Specialization for CompactArcStore. -template -class CompactArcState> { - public: - using Arc = typename ArcCompactor::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - using CompactStore = CompactArcStore; - using Compactor = CompactArcCompactor; - - CompactArcState() = default; - - CompactArcState(const Compactor *compactor, StateId s) - : arc_compactor_(compactor->GetArcCompactor()), s_(s) { - Init(compactor); - } - - void Set(const Compactor *compactor, StateId s) { - arc_compactor_ = compactor->GetArcCompactor(); - s_ = s; - has_final_ = false; - Init(compactor); - } - - StateId GetStateId() const { return s_; } - - Weight Final() const { - if (!has_final_) return Weight::Zero(); - return arc_compactor_->Expand(s_, *(compacts_ - 1), kArcWeightValue).weight; - } - - size_t NumArcs() const { return num_arcs_; } - - Arc GetArc(size_t i, uint8_t flags) const { - return arc_compactor_->Expand(s_, compacts_[i], flags); - } - - private: - void Init(const Compactor *compactor) { - const auto *store = compactor->GetCompactStore(); - U offset; - if (!compactor->HasFixedOutdegree()) { // Variable out-degree compactor. - offset = store->States(s_); - num_arcs_ = store->States(s_ + 1) - offset; - } else { // Fixed out-degree compactor. - offset = s_ * arc_compactor_->Size(); - num_arcs_ = arc_compactor_->Size(); - } - if (num_arcs_ > 0) { - compacts_ = &(store->Compacts(offset)); - if (arc_compactor_->Expand(s_, *compacts_, kArcILabelValue).ilabel == - kNoStateId) { - ++compacts_; - --num_arcs_; - has_final_ = true; - } - } - } - - private: - const ArcCompactor *arc_compactor_ = nullptr; // Borrowed reference. - const typename ArcCompactor::Element *compacts_ = - nullptr; // Borrowed reference. - StateId s_ = kNoStateId; - U num_arcs_ = 0; - bool has_final_ = false; -}; - -template -void Cast(const F &, G *); - -template -bool WriteCompactArcFst( - const FST &fst, - const typename CompactArcFST::Compactor::ArcCompactor &arc_compactor, - std::ostream &strm, const FstWriteOptions &opts); - -namespace internal { - -// Implementation class for CompactFst, which contains parametrizeable -// Fst data storage (CompactArcStore by default) and Fst cache. -// C's copy constructor must make a thread-safe copy. -template > -class CompactFstImpl - : public CacheBaseImpl { - public: - using Weight = typename Arc::Weight; - using StateId = typename Arc::StateId; - using Compactor = C; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::Properties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - using FstImpl::WriteHeader; - - using ImplBase = CacheBaseImpl; - using ImplBase::HasArcs; - using ImplBase::HasFinal; - using ImplBase::HasStart; - using ImplBase::PushArc; - using ImplBase::SetArcs; - using ImplBase::SetFinal; - using ImplBase::SetStart; - - CompactFstImpl() - : ImplBase(CompactFstOptions()), - compactor_(std::make_shared()) { - SetType(Compactor::Type()); - SetProperties(kNullProperties | kStaticProperties); - } - - // Constructs a CompactFstImpl, creating a new Compactor using - // Compactor(fst, compactor); this uses the compactor arg only for optional - // information, such as compression level. See the Compactor interface - // description. - CompactFstImpl(const Fst &fst, std::shared_ptr compactor, - const CompactFstOptions &opts) - : ImplBase(opts), - compactor_(std::make_shared(fst, std::move(compactor))) { - SetType(Compactor::Type()); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - if (compactor_->Error()) SetProperties(kError, kError); - uint64_t copy_properties = - fst.Properties(kMutable, false) - ? fst.Properties(kCopyProperties, true) - : CheckProperties( - fst, kCopyProperties & ~kWeightedCycles & ~kUnweightedCycles, - kCopyProperties); - if ((copy_properties & kError) || !compactor_->IsCompatible(fst)) { - FSTERROR() << "CompactFstImpl: Input Fst incompatible with compactor"; - SetProperties(kError, kError); - return; - } - SetProperties(compactor_->Properties(copy_properties) | kStaticProperties); - } - - CompactFstImpl(std::shared_ptr compactor, - const CompactFstOptions &opts) - : ImplBase(opts), compactor_(std::move(compactor)) { - SetType(Compactor::Type()); - SetProperties(kStaticProperties | compactor_->Properties(0)); - if (compactor_->Error()) SetProperties(kError, kError); - } - - // Makes a thread-safe copy; requires that Compactor's copy constructor - // does so as well. - CompactFstImpl(const CompactFstImpl &impl) - : ImplBase(impl), - compactor_(impl.compactor_ == nullptr - ? std::make_shared() - : std::make_shared(*impl.compactor_)) { - SetType(impl.Type()); - SetProperties(impl.Properties()); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - // Allows to change the cache store from OtherCacheStore to CacheStore. - template - explicit CompactFstImpl( - const CompactFstImpl &impl) - : ImplBase(CacheOptions(impl.GetCacheGc(), impl.GetCacheLimit())), - compactor_(impl.compactor_ == nullptr - ? std::make_shared() - : std::make_shared(*impl.compactor_)) { - SetType(impl.Type()); - SetProperties(impl.Properties()); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - StateId Start() { - if (!HasStart()) SetStart(compactor_->Start()); - return ImplBase::Start(); - } - - Weight Final(StateId s) { - if (HasFinal(s)) return ImplBase::Final(s); - compactor_->SetState(s, &state_); - return state_.Final(); - } - - StateId NumStates() const { - if (Properties(kError)) return 0; - return compactor_->NumStates(); - } - - size_t NumArcs(StateId s) { - if (HasArcs(s)) return ImplBase::NumArcs(s); - compactor_->SetState(s, &state_); - return state_.NumArcs(); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s) && !Properties(kILabelSorted)) Expand(s); - if (HasArcs(s)) return ImplBase::NumInputEpsilons(s); - return CountEpsilons(s, false); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s) && !Properties(kOLabelSorted)) Expand(s); - if (HasArcs(s)) return ImplBase::NumOutputEpsilons(s); - return CountEpsilons(s, true); - } - - size_t CountEpsilons(StateId s, bool output_epsilons) { - compactor_->SetState(s, &state_); - const uint8_t flags = output_epsilons ? kArcOLabelValue : kArcILabelValue; - size_t num_eps = 0; - const size_t num_arcs = state_.NumArcs(); - for (size_t i = 0; i < num_arcs; ++i) { - const auto &arc = state_.GetArc(i, flags); - const auto label = output_epsilons ? arc.olabel : arc.ilabel; - if (label == 0) { - ++num_eps; - } else if (label > 0) { - break; - } - } - return num_eps; - } - - static CompactFstImpl *Read(std::istream &strm, const FstReadOptions &opts) { - auto impl = std::make_unique(); - FstHeader hdr; - if (!impl->ReadHeader(strm, opts, kMinFileVersion, &hdr)) { - return nullptr; - } - // Ensures compatibility. - if (hdr.Version() == kAlignedFileVersion) { - hdr.SetFlags(hdr.GetFlags() | FstHeader::IS_ALIGNED); - } - impl->compactor_ = - std::shared_ptr(Compactor::Read(strm, opts, hdr)); - if (!impl->compactor_) { - return nullptr; - } - return impl.release(); - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const { - FstHeader hdr; - hdr.SetStart(compactor_->Start()); - hdr.SetNumStates(compactor_->NumStates()); - hdr.SetNumArcs(compactor_->NumArcs()); - // Ensures compatibility. - const auto file_version = opts.align ? kAlignedFileVersion : kFileVersion; - WriteHeader(strm, opts, file_version, &hdr); - return compactor_->Write(strm, opts); - } - - // Provides information needed for generic state iterator. - void InitStateIterator(StateIteratorData *data) const { - data->base = nullptr; - data->nstates = compactor_->NumStates(); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - ImplBase::InitArcIterator(s, data); - } - - void Expand(StateId s) { - compactor_->SetState(s, &state_); - const size_t num_arcs = state_.NumArcs(); - for (size_t i = 0; i < num_arcs; ++i) - PushArc(s, state_.GetArc(i, kArcValueFlags)); - SetArcs(s); - if (!HasFinal(s)) SetFinal(s, state_.Final()); - } - - const Compactor *GetCompactor() const { return compactor_.get(); } - Compactor *MutableCompactor() { return compactor_.get(); } - std::shared_ptr SharedCompactor() { return compactor_; } - void SetCompactor(std::shared_ptr compactor) { - // TODO(allauzen): is this correct? is this needed? - // TODO(allauzen): consider removing and forcing this through direct calls - // to compactor. - compactor_ = std::move(compactor); - } - - // Properties always true of this FST class. - static constexpr uint64_t kStaticProperties = kExpanded; - - protected: - template - explicit CompactFstImpl( - const CompactFstImpl &impl) - : compactor_(std::make_shared(*impl.GetCompactor())) { - SetType(impl.Type()); - SetProperties(impl.Properties()); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - private: - // For k*Version constants. - template - friend bool ::fst::WriteCompactArcFst( - const FST &fst, - const typename CompactArcFST::Compactor::ArcCompactor &arc_compactor, - std::ostream &strm, const FstWriteOptions &opts); - - // Current unaligned file format version. - static constexpr int kFileVersion = 2; - // Current aligned file format version. - static constexpr int kAlignedFileVersion = 1; - // Minimum file format version supported. - static constexpr int kMinFileVersion = 1; - - std::shared_ptr compactor_; - typename Compactor::State state_; -}; - -// Returns the compactor for the CompactFst; intended to be called as -// GetCompactor(fst), which returns the compactor only if it -// is of the specified type and otherwise nullptr (via the overload below). -template -const Compactor *GetCompactor(const CompactFst &fst) { - return fst.GetCompactor(); -} - -template -const Compactor *GetCompactor(const Fst &fst) { - return nullptr; -} - -} // namespace internal - -// This class attaches interface to implementation and handles reference -// counting, delegating most methods to ImplToExpandedFst. -// (Template argument defaults are declared in fst-decl.h.) -template -class CompactFst - : public ImplToExpandedFst> { - public: - template - void friend Cast(const F &, G *); - - using Arc = A; - using StateId = typename Arc::StateId; - using Compactor = C; - using Impl = internal::CompactFstImpl; - using Store = CacheStore; // for CacheArcIterator - - friend class StateIterator; - friend class ArcIterator; - - CompactFst() : ImplToExpandedFst(std::make_shared()) {} - - explicit CompactFst(const Fst &fst, - const CompactFstOptions &opts = CompactFstOptions()) - : CompactFst(fst, std::make_shared(fst), opts) {} - - // Constructs a CompactFst, creating a new Compactor using - // Compactor(fst, compactor); this uses the compactor arg only for optional - // information, such as compression level. See the Compactor interface - // description. - CompactFst(const Fst &fst, std::shared_ptr compactor, - const CompactFstOptions &opts = CompactFstOptions()) - : ImplToExpandedFst( - std::make_shared(fst, std::move(compactor), opts)) {} - - // Convenience constructor taking a Compactor rvalue ref. Avoids - // clutter of make_shared at call site. - // Constructs a CompactFst, creating a new Compactor using - // Compactor(fst, compactor); this uses the compactor arg only for optional - // information, such as compression level. See the Compactor interface - // description. - CompactFst(const Fst &fst, Compactor &&compactor, - const CompactFstOptions &opts = CompactFstOptions()) - : CompactFst(fst, std::make_shared(std::move(compactor)), - opts) {} - - explicit CompactFst(std::shared_ptr compactor, - const CompactFstOptions &opts = CompactFstOptions()) - : ImplToExpandedFst( - std::make_shared(std::move(compactor), opts)) {} - - // See Fst<>::Copy() for doc. - CompactFst(const CompactFst &fst, bool safe = false) - : ImplToExpandedFst(fst, safe) {} - - // Get a copy of this CompactFst. See Fst<>::Copy() for further doc. - CompactFst *Copy(bool safe = false) const override { - return new CompactFst(*this, safe); - } - - // Read a CompactFst from an input stream; return nullptr on error - static CompactFst *Read(std::istream &strm, const FstReadOptions &opts) { - auto *impl = Impl::Read(strm, opts); - return impl ? new CompactFst(std::shared_ptr(impl)) : nullptr; - } - - // Read a CompactFst from a file; return nullptr on error - // Empty source reads from standard input - static CompactFst *Read(std::string_view source) { - auto *impl = ImplToExpandedFst::Read(source); - return impl ? new CompactFst(std::shared_ptr(impl)) : nullptr; - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const override { - return GetImpl()->Write(strm, opts); - } - - bool Write(const std::string &source) const override { - return Fst::WriteFile(source); - } - - void InitStateIterator(StateIteratorData *data) const override { - GetImpl()->InitStateIterator(data); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - MatcherBase *InitMatcher(MatchType match_type) const override { - return new SortedMatcher(*this, match_type); - } - - const Compactor *GetCompactor() const { return GetImpl()->GetCompactor(); } - - void SetCompactor(std::shared_ptr compactor) { - GetMutableImpl()->SetCompactor(std::move(compactor)); - } - - private: - using ImplToFst>::GetImpl; - using ImplToFst>::GetMutableImpl; - - explicit CompactFst(std::shared_ptr impl) - : ImplToExpandedFst(std::move(impl)) {} - - CompactFst &operator=(const CompactFst &fst) = delete; -}; - -// Writes FST in ArcCompacted format, with a possible pass over the machine -// before writing to compute the number of states and arcs. -template -bool WriteCompactArcFst( - const FST &fst, - const typename CompactArcFST::Compactor::ArcCompactor &arc_compactor, - std::ostream &strm, const FstWriteOptions &opts) { - using Arc = typename CompactArcFST::Arc; - using Compactor = typename CompactArcFST::Compactor; - using ArcCompactor = typename Compactor::ArcCompactor; - using CompactStore = typename Compactor::CompactStore; - using Element = typename ArcCompactor::Element; - using Impl = typename CompactArcFST::Impl; - using Unsigned = typename Compactor::Unsigned; - using Weight = typename Arc::Weight; - const auto file_version = - opts.align ? Impl::kAlignedFileVersion : Impl::kFileVersion; - size_t num_arcs = -1; - size_t num_states = -1; - auto first_pass_arc_compactor = arc_compactor; - // Note that GetCompactor will only return non-null if the compactor has the - // exact type Compactor == CompactArcFst::Compactor. This is what we want; - // other types must do an extra pass to set the arc compactor state. - if (const Compactor *const compactor = - internal::GetCompactor(fst)) { - num_arcs = compactor->NumArcs(); - num_states = compactor->NumStates(); - first_pass_arc_compactor = *compactor->GetArcCompactor(); - } else { - // A first pass is needed to compute the state of the compactor, which - // is saved ahead of the rest of the data structures. This unfortunately - // means forcing a complete double compaction when writing in this format. - // TODO(allauzen): eliminate mutable state from compactors. - num_arcs = 0; - num_states = 0; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - ++num_states; - if (fst.Final(s) != Weight::Zero()) { - first_pass_arc_compactor.Compact( - s, Arc(kNoLabel, kNoLabel, fst.Final(s), kNoStateId)); - } - for (ArcIterator aiter(fst, s); !aiter.Done(); aiter.Next()) { - ++num_arcs; - first_pass_arc_compactor.Compact(s, aiter.Value()); - } - } - } - FstHeader hdr; - hdr.SetStart(fst.Start()); - hdr.SetNumStates(num_states); - hdr.SetNumArcs(num_arcs); - std::string type = "compact"; - if (sizeof(Unsigned) != sizeof(uint32_t)) { - type += std::to_string(CHAR_BIT * sizeof(Unsigned)); - } - type += "_"; - type += ArcCompactor::Type(); - if (CompactStore::Type() != "compact") { - type += "_"; - type += CompactStore::Type(); - } - const auto copy_properties = fst.Properties(kCopyProperties, true); - if ((copy_properties & kError) || !arc_compactor.Compatible(fst)) { - FSTERROR() << "Fst incompatible with compactor"; - return false; - } - uint64_t properties = copy_properties | Impl::kStaticProperties; - internal::FstImpl::WriteFstHeader(fst, strm, opts, file_version, type, - properties, &hdr); - first_pass_arc_compactor.Write(strm); - if (first_pass_arc_compactor.Size() == -1) { - if (opts.align && !AlignOutput(strm)) { - LOG(ERROR) << "WriteCompactArcFst: Alignment failed: " << opts.source; - return false; - } - Unsigned compacts = 0; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - strm.write(reinterpret_cast(&compacts), sizeof(compacts)); - if (fst.Final(s) != Weight::Zero()) { - ++compacts; - } - compacts += fst.NumArcs(s); - } - strm.write(reinterpret_cast(&compacts), sizeof(compacts)); - } - if (opts.align && !AlignOutput(strm)) { - LOG(ERROR) << "Could not align file during write after writing states"; - } - const auto &second_pass_arc_compactor = arc_compactor; - Element element; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - if (fst.Final(s) != Weight::Zero()) { - element = second_pass_arc_compactor.Compact( - s, Arc(kNoLabel, kNoLabel, fst.Final(s), kNoStateId)); - strm.write(reinterpret_cast(&element), sizeof(element)); - } - for (ArcIterator aiter(fst, s); !aiter.Done(); aiter.Next()) { - element = second_pass_arc_compactor.Compact(s, aiter.Value()); - strm.write(reinterpret_cast(&element), sizeof(element)); - } - } - strm.flush(); - if (!strm) { - LOG(ERROR) << "WriteCompactArcFst: Write failed: " << opts.source; - return false; - } - return true; -} - -// Specialization for CompactFst; see generic version in fst.h for sample -// usage (but use the CompactFst type!). This version should inline. -template -class StateIterator> { - public: - using StateId = typename Arc::StateId; - - explicit StateIterator(const CompactFst &fst) - : nstates_(fst.NumStates()), s_(0) {} - - bool Done() const { return s_ >= nstates_; } - - StateId Value() const { return s_; } - - void Next() { ++s_; } - - void Reset() { s_ = 0; } - - private: - StateId nstates_; - StateId s_; -}; - -// Specialization for CompactFst. Never caches, -// always iterates over the underlying compact elements. -template -class ArcIterator> { - public: - using StateId = typename Arc::StateId; - using State = typename Compactor::State; - - ArcIterator(const CompactFst &fst, StateId s) - : state_(fst.GetMutableImpl()->MutableCompactor(), s), - pos_(0), - num_arcs_(state_.NumArcs()), - flags_(kArcValueFlags) {} - - bool Done() const { return pos_ >= num_arcs_; } - - const Arc &Value() const { - arc_ = state_.GetArc(pos_, flags_); - return arc_; - } - - void Next() { ++pos_; } - - size_t Position() const { return pos_; } - - void Reset() { pos_ = 0; } - - void Seek(size_t pos) { pos_ = pos; } - - uint8_t Flags() const { return flags_; } - - void SetFlags(uint8_t flags, uint8_t mask) { - flags_ &= ~mask; - flags_ |= (flags & kArcValueFlags); - } - - private: - State state_; - size_t pos_; - // Cache the value of NumArcs(), since it is used in Done() and may be slow. - size_t num_arcs_; - mutable Arc arc_; - uint8_t flags_; -}; - -// ArcCompactor for unweighted string FSTs. -template -class StringCompactor { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Element = Label; - - Element Compact(StateId s, const Arc &arc) const { return arc.ilabel; } - - Arc Expand(StateId s, const Element &p, - uint8_t flags = kArcValueFlags) const { - return Arc(p, p, Weight::One(), p != kNoLabel ? s + 1 : kNoStateId); - } - - constexpr ssize_t Size() const { return 1; } - - constexpr uint64_t Properties() const { return kCompiledStringProperties; } - - bool Compatible(const Fst &fst) const { - const auto props = Properties(); - return fst.Properties(props, true) == props; - } - - static const std::string &Type() { - static const std::string *const type = new std::string("string"); - return *type; - } - - bool Write(std::ostream &strm) const { return true; } - - static StringCompactor *Read(std::istream &strm) { - return new StringCompactor; - } -}; - -// ArcCompactor for weighted string FSTs. -template -class WeightedStringCompactor { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Element = std::pair; - - Element Compact(StateId s, const Arc &arc) const { - return std::make_pair(arc.ilabel, arc.weight); - } - - Arc Expand(StateId s, const Element &p, - uint8_t flags = kArcValueFlags) const { - return Arc(p.first, p.first, p.second, - p.first != kNoLabel ? s + 1 : kNoStateId); - } - - constexpr ssize_t Size() const { return 1; } - - constexpr uint64_t Properties() const { return kString | kAcceptor; } - - bool Compatible(const Fst &fst) const { - const auto props = Properties(); - return fst.Properties(props, true) == props; - } - - static const std::string &Type() { - static const std::string *const type = new std::string("weighted_string"); - return *type; - } - - bool Write(std::ostream &strm) const { return true; } - - static WeightedStringCompactor *Read(std::istream &strm) { - return new WeightedStringCompactor; - } -}; - -// ArcCompactor for unweighted acceptor FSTs. -template -class UnweightedAcceptorCompactor { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Element = std::pair; - - Element Compact(StateId s, const Arc &arc) const { - return std::make_pair(arc.ilabel, arc.nextstate); - } - - Arc Expand(StateId s, const Element &p, - uint8_t flags = kArcValueFlags) const { - return Arc(p.first, p.first, Weight::One(), p.second); - } - - constexpr ssize_t Size() const { return -1; } - - constexpr uint64_t Properties() const { return kAcceptor | kUnweighted; } - - bool Compatible(const Fst &fst) const { - const auto props = Properties(); - return fst.Properties(props, true) == props; - } - - static const std::string &Type() { - static const std::string *const type = - new std::string("unweighted_acceptor"); - return *type; - } - - bool Write(std::ostream &strm) const { return true; } - - static UnweightedAcceptorCompactor *Read(std::istream &istrm) { - return new UnweightedAcceptorCompactor; - } -}; - -// ArcCompactor for weighted acceptor FSTs. -template -class AcceptorCompactor { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Element = std::pair, StateId>; - - Element Compact(StateId s, const Arc &arc) const { - return std::make_pair(std::make_pair(arc.ilabel, arc.weight), - arc.nextstate); - } - - Arc Expand(StateId s, const Element &p, - uint8_t flags = kArcValueFlags) const { - return Arc(p.first.first, p.first.first, p.first.second, p.second); - } - - constexpr ssize_t Size() const { return -1; } - - constexpr uint64_t Properties() const { return kAcceptor; } - - bool Compatible(const Fst &fst) const { - const auto props = Properties(); - return fst.Properties(props, true) == props; - } - - static const std::string &Type() { - static const std::string *const type = new std::string("acceptor"); - return *type; - } - - bool Write(std::ostream &strm) const { return true; } - - static AcceptorCompactor *Read(std::istream &strm) { - return new AcceptorCompactor; - } -}; - -// ArcCompactor for unweighted FSTs. -template -class UnweightedCompactor { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Element = std::pair, StateId>; - - Element Compact(StateId s, const Arc &arc) const { - return std::make_pair(std::make_pair(arc.ilabel, arc.olabel), - arc.nextstate); - } - - Arc Expand(StateId s, const Element &p, - uint8_t flags = kArcValueFlags) const { - return Arc(p.first.first, p.first.second, Weight::One(), p.second); - } - - constexpr ssize_t Size() const { return -1; } - - constexpr uint64_t Properties() const { return kUnweighted; } - - bool Compatible(const Fst &fst) const { - const auto props = Properties(); - return fst.Properties(props, true) == props; - } - - static const std::string &Type() { - static const std::string *const type = new std::string("unweighted"); - return *type; - } - - bool Write(std::ostream &strm) const { return true; } - - static UnweightedCompactor *Read(std::istream &strm) { - return new UnweightedCompactor; - } -}; - -template -using CompactStringFst = CompactArcFst, Unsigned>; - -template -using CompactWeightedStringFst = - CompactArcFst, Unsigned>; - -template -using CompactAcceptorFst = CompactArcFst, Unsigned>; - -template -using CompactUnweightedFst = - CompactArcFst, Unsigned>; - -template -using CompactUnweightedAcceptorFst = - CompactArcFst, Unsigned>; - -using StdCompactStringFst = CompactStringFst; - -using StdCompactWeightedStringFst = CompactWeightedStringFst; - -using StdCompactAcceptorFst = CompactAcceptorFst; - -using StdCompactUnweightedFst = CompactUnweightedFst; - -using StdCompactUnweightedAcceptorFst = - CompactUnweightedAcceptorFst; - -// Convenience function to make a CompactStringFst from a sequence -// of Arc::Labels. LabelIterator must be an input iterator. -template -inline CompactStringFst MakeCompactStringFst( - const LabelIterator begin, const LabelIterator end) { - using CompactStringFst = CompactStringFst; - using Compactor = typename CompactStringFst::Compactor; - return CompactStringFst(std::make_shared(begin, end)); -} - -template -inline StdCompactStringFst MakeStdCompactStringFst(const LabelIterator begin, - const LabelIterator end) { - return MakeCompactStringFst(begin, end); -} - -} // namespace fst - -#endif // FST_COMPACT_FST_H_ diff --git a/contrib/fstlib/fst/compat.h b/contrib/fstlib/fst/compat.h deleted file mode 100644 index 381b4c1..0000000 --- a/contrib/fstlib/fst/compat.h +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. - -#ifndef FST_COMPAT_H_ -#define FST_COMPAT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__GNUC__) || defined(__clang__) -#define OPENFST_DEPRECATED(message) __attribute__((deprecated(message))) -#elif defined(_MSC_VER) -#define OPENFST_DEPRECATED(message) [[deprecated(message)]] -#else -#define OPENFST_DEPRECATED(message) -#endif - -namespace fst { - -// Downcasting. - -template -inline To down_cast(From *f) { - return static_cast(f); -} - -template -inline To down_cast(From &f) { - return static_cast(f); -} - -// Bitcasting. -template -inline Dest bit_cast(const Source &source) { - static_assert(sizeof(Dest) == sizeof(Source), - "Bitcasting unsafe for specified types"); - Dest dest; - memcpy(&dest, &source, sizeof(dest)); - return dest; -} - -template -T UnalignedLoad(const void *p) { - T t; - memcpy(&t, p, sizeof t); - return t; -} - -namespace internal { - -// TODO(kbg): Remove this once we migrate to C++20. -template -struct type_identity { - using type = T; -}; - -template -using type_identity_t = typename type_identity::type; - -} // namespace internal - -template -constexpr To implicit_cast(typename internal::type_identity_t to) { - return to; -} - -// Checksums. -class CheckSummer { - public: - CheckSummer(); - - void Reset(); - - void Update(std::string_view data); - - std::string Digest() { return check_sum_; } - - private: - static constexpr int kCheckSumLength = 32; - int count_; - std::string check_sum_; - - CheckSummer(const CheckSummer &) = delete; - CheckSummer &operator=(const CheckSummer &) = delete; -}; - -// Defines make_unique_for_overwrite using a standard definition that should be -// compatible with the C++20 definition. That is, all compiling uses of -// `std::make_unique_for_overwrite` should have the same result with -// `fst::make_unique_for_overwrite`. Note that the reverse doesn't -// necessarily hold. -// TODO(kbg): Remove these once we migrate to C++20. - -template -std::unique_ptr make_unique_for_overwrite() { - return std::unique_ptr(new T); -} - -template -std::unique_ptr make_unique_for_overwrite(size_t n) { - return std::unique_ptr(new std::remove_extent_t[n]); -} - -template -std::unique_ptr WrapUnique(T *ptr) { - return std::unique_ptr(ptr); -} - -// Range utilities - -// A range adaptor for a pair of iterators. -// -// This just wraps two iterators into a range-compatible interface. Nothing -// fancy at all. -template -class iterator_range { - public: - using iterator = IteratorT; - using const_iterator = IteratorT; - using value_type = typename std::iterator_traits::value_type; - - iterator_range() : begin_iterator_(), end_iterator_() {} - iterator_range(IteratorT begin_iterator, IteratorT end_iterator) - : begin_iterator_(std::move(begin_iterator)), - end_iterator_(std::move(end_iterator)) {} - - IteratorT begin() const { return begin_iterator_; } - IteratorT end() const { return end_iterator_; } - - private: - IteratorT begin_iterator_, end_iterator_; -}; - -// Convenience function for iterating over sub-ranges. -// -// This provides a bit of syntactic sugar to make using sub-ranges -// in for loops a bit easier. Analogous to std::make_pair(). -template -iterator_range make_range(T x, T y) { - return iterator_range(std::move(x), std::move(y)); -} - -// String munging. - -namespace internal { - -// Computes size of joined string. -template -size_t GetResultSize(const std::vector &elements, size_t s_size) { - const auto lambda = [](size_t partial, const S &right) { - return partial + right.size(); - }; - return std::accumulate(elements.begin(), elements.end(), 0, lambda) + - elements.size() * s_size - s_size; -} - -} // namespace internal - -template -std::string StringJoin(const std::vector &elements, std::string_view delim) { - std::string result; - if (elements.empty()) return result; - const size_t s_size = delim.size(); - result.reserve(internal::GetResultSize(elements, s_size)); - auto it = elements.begin(); - result.append(it->data(), it->size()); - for (++it; it != elements.end(); ++it) { - result.append(delim.data(), s_size); - result.append(it->data(), it->size()); - } - return result; -} - -template -std::string StringJoin(const std::vector &elements, char delim) { - const std::string_view view_delim(&delim, 1); - return StringJoin(elements, view_delim); -} - -struct SkipEmpty {}; - -struct ByAnyChar { - public: - explicit ByAnyChar(std::string_view sp) : delimiters(sp) {} - - std::string delimiters; -}; - -namespace internal { - -class StringSplitter { - public: - using const_iterator = std::vector::const_iterator; - using value_type = std::string_view; - - StringSplitter(std::string_view string, std::string delim, - bool skip_empty = false) - : string_(std::move(string)), - delim_(std::move(delim)), - skip_empty_(skip_empty), - vec_(SplitToSv()) {} - - inline operator // NOLINT(google-explicit-constructor) - std::vector() && { - return std::move(vec_); - } - - inline operator // NOLINT(google-explicit-constructor) - std::vector() { - std::vector str_vec(vec_.begin(), vec_.end()); - return str_vec; - } - - const_iterator begin() const { return vec_.begin(); } - const_iterator end() const { return vec_.end(); } - - private: - std::vector SplitToSv(); - - std::string_view string_; - std::string delim_; - bool skip_empty_; - std::vector vec_; -}; - -} // namespace internal - -// `StrSplit` replacements. Only support splitting on `char` or -// `ByAnyChar` (notable not on a multi-char string delimiter), and with or -// without `SkipEmpty`. -internal::StringSplitter StrSplit(std::string_view full, ByAnyChar delim); -internal::StringSplitter StrSplit(std::string_view full, char delim); -internal::StringSplitter StrSplit(std::string_view full, ByAnyChar delim, - SkipEmpty); -internal::StringSplitter StrSplit(std::string_view full, char delim, SkipEmpty); - -void StripTrailingAsciiWhitespace(std::string *full); - -std::string_view StripTrailingAsciiWhitespace(std::string_view full); - -class StringOrInt { - public: - template >> - StringOrInt(T s) : str_(std::string(s)) {} // NOLINT - - StringOrInt(int i) { // NOLINT - str_ = std::to_string(i); - } - - const std::string &Get() const { return str_; } - - private: - std::string str_; -}; - -// TODO(kbg): Make this work with variadic template, maybe. - -inline std::string StrCat(const StringOrInt &s1, const StringOrInt &s2) { - return s1.Get() + s2.Get(); -} - -inline std::string StrCat(const StringOrInt &s1, const StringOrInt &s2, - const StringOrInt &s3) { - return s1.Get() + StrCat(s2, s3); -} - -inline std::string StrCat(const StringOrInt &s1, const StringOrInt &s2, - const StringOrInt &s3, const StringOrInt &s4) { - return s1.Get() + StrCat(s2, s3, s4); -} - -inline std::string StrCat(const StringOrInt &s1, const StringOrInt &s2, - const StringOrInt &s3, const StringOrInt &s4, - const StringOrInt &s5) { - return s1.Get() + StrCat(s2, s3, s4, s5); -} - -// TODO(agutkin): Remove this once we migrate to C++20, where `starts_with` -// is available. -inline bool StartsWith(std::string_view text, std::string_view prefix) { - return prefix.empty() || - (text.size() >= prefix.size() && - memcmp(text.data(), prefix.data(), prefix.size()) == 0); -} - -inline bool ConsumePrefix(std::string_view *s, std::string_view expected) { - if (!StartsWith(*s, expected)) return false; - s->remove_prefix(expected.size()); - return true; -} - -} // namespace fst - -#endif // FST_COMPAT_H_ diff --git a/contrib/fstlib/fst/complement.h b/contrib/fstlib/fst/complement.h deleted file mode 100644 index 1efc66b..0000000 --- a/contrib/fstlib/fst/complement.h +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to complement an FST. - -#ifndef FST_COMPLEMENT_H_ -#define FST_COMPLEMENT_H_ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -template -class ComplementFst; - -namespace internal { - -// Implementation of delayed ComplementFst. The algorithm used completes the -// (deterministic) FSA and then exchanges final and non-final states. -// Completion, i.e. ensuring that all labels can be read from every state, is -// accomplished by using ρ-labels, which match all labels that are otherwise -// not found leaving a state. The first state in the output is reserved to be a -// new state that is the destination of all ρ-labels. Each remaining output -// state s corresponds to input state s - 1. The first arc in the output at -// these states is the ρ-label, the remaining arcs correspond to the input -// arcs. -template -class ComplementFstImpl : public FstImpl { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - friend class StateIterator>; - friend class ArcIterator>; - - explicit ComplementFstImpl(const Fst &fst) : fst_(fst.Copy()) { - SetType("complement"); - const auto props = fst.Properties(kILabelSorted, false); - SetProperties(ComplementProperties(props), kCopyProperties); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - } - - ComplementFstImpl(const ComplementFstImpl &impl) - : fst_(impl.fst_->Copy()) { - SetType("complement"); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - StateId Start() const { - if (Properties(kError)) return kNoStateId; - const auto start = fst_->Start(); - return start != kNoStateId ? start + 1 : 0; - } - - // Exchange final and non-final states; makes ρ-destination state final. - Weight Final(StateId s) const { - if (s == 0 || fst_->Final(s - 1) == Weight::Zero()) { - return Weight::One(); - } else { - return Weight::Zero(); - } - } - - size_t NumArcs(StateId s) const { - return s == 0 ? 1 : fst_->NumArcs(s - 1) + 1; - } - - size_t NumInputEpsilons(StateId s) const { - return s == 0 ? 0 : fst_->NumInputEpsilons(s - 1); - } - - size_t NumOutputEpsilons(StateId s) const { - return s == 0 ? 0 : fst_->NumOutputEpsilons(s - 1); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && fst_->Properties(kError, false)) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - private: - std::unique_ptr> fst_; -}; - -} // namespace internal - -// Complements an automaton. This is a library-internal operation that -// introduces a (negative) ρ-label; use Difference/DifferenceFst in user code, -// which will not see this label. This version is a delayed FST. -// -// This class attaches interface to implementation and handles -// reference counting, delegating most methods to ImplToFst. -template -class ComplementFst : public ImplToFst> { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Impl = internal::ComplementFstImpl; - - friend class StateIterator>; - friend class ArcIterator>; - - explicit ComplementFst(const Fst &fst) - : ImplToFst(std::make_shared(fst)) { - static constexpr auto props = - kUnweighted | kNoEpsilons | kIDeterministic | kAcceptor; - if (fst.Properties(props, true) != props) { - FSTERROR() << "ComplementFst: Argument not an unweighted " - << "epsilon-free deterministic acceptor"; - GetImpl()->SetProperties(kError, kError); - } - } - - // See Fst<>::Copy() for doc. - ComplementFst(const ComplementFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Gets a copy of this FST. See Fst<>::Copy() for further doc. - ComplementFst *Copy(bool safe = false) const override { - return new ComplementFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - inline void InitArcIterator(StateId s, - ArcIteratorData *data) const override; - - // Label that represents the ρ-transition; we use a negative value private to - // the library and which will preserve FST label sort order. - static constexpr Label kRhoLabel = -2; - - private: - using ImplToFst::GetImpl; - - ComplementFst &operator=(const ComplementFst &) = delete; -}; - -// Specialization for ComplementFst. -template -class StateIterator> : public StateIteratorBase { - public: - using StateId = typename Arc::StateId; - - explicit StateIterator(const ComplementFst &fst) - : siter_(*fst.GetImpl()->fst_), s_(0) {} - - bool Done() const final { return s_ > 0 && siter_.Done(); } - - StateId Value() const final { return s_; } - - void Next() final { - if (s_ != 0) siter_.Next(); - ++s_; - } - - void Reset() final { - siter_.Reset(); - s_ = 0; - } - - private: - StateIterator> siter_; - StateId s_; -}; - -// Specialization for ComplementFst. -template -class ArcIterator> : public ArcIteratorBase { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - ArcIterator(const ComplementFst &fst, StateId s) : s_(s), pos_(0) { - if (s_ != 0) { - aiter_ = - std::make_unique>>(*fst.GetImpl()->fst_, s - 1); - } - } - - bool Done() const final { - if (s_ != 0) { - return pos_ > 0 && aiter_->Done(); - } else { - return pos_ > 0; - } - } - - // Adds the ρ-label to the ρ destination state. - const Arc &Value() const final { - if (pos_ == 0) { - arc_.ilabel = arc_.olabel = ComplementFst::kRhoLabel; - arc_.weight = Weight::One(); - arc_.nextstate = 0; - } else { - arc_ = aiter_->Value(); - ++arc_.nextstate; - } - return arc_; - } - - void Next() final { - if (s_ != 0 && pos_ > 0) aiter_->Next(); - ++pos_; - } - - size_t Position() const final { return pos_; } - - void Reset() final { - if (s_ != 0) aiter_->Reset(); - pos_ = 0; - } - - void Seek(size_t a) final { - if (s_ != 0) { - if (a == 0) { - aiter_->Reset(); - } else { - aiter_->Seek(a - 1); - } - } - pos_ = a; - } - - uint8_t Flags() const final { return kArcValueFlags; } - - void SetFlags(uint8_t, uint8_t) final {} - - private: - std::unique_ptr>> aiter_; - StateId s_; - size_t pos_; - mutable Arc arc_; -}; - -template -inline void ComplementFst::InitStateIterator( - StateIteratorData *data) const { - data->base = std::make_unique>>(*this); -} - -template -inline void ComplementFst::InitArcIterator( - StateId s, ArcIteratorData *data) const { - data->base = std::make_unique>>(*this, s); -} - -// Useful alias when using StdArc. -using StdComplementFst = ComplementFst; - -} // namespace fst - -#endif // FST_COMPLEMENT_H_ diff --git a/contrib/fstlib/fst/compose-filter.h b/contrib/fstlib/fst/compose-filter.h deleted file mode 100644 index cf2733c..0000000 --- a/contrib/fstlib/fst/compose-filter.h +++ /dev/null @@ -1,591 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes for filtering the composition matches, e.g. for correct epsilon -// handling. - -#ifndef FST_COMPOSE_FILTER_H_ -#define FST_COMPOSE_FILTER_H_ - -#include -#include -#include - -#include -#include // For optional argument declarations -#include -#include -#include - -namespace fst { - -// Composition filters determine which matches are allowed to proceed. The -// filter's state is represeted by the type ComposeFilter::FilterState. -// The basic filters handle correct epsilon matching. Their interface is: -// -// template -// class ComposeFilter { -// public: -// using Matcher1 = ...; -// using Matcher2 = ...; -// using FST1 = typename M1::FST; -// using FST2 = typename M2::FST; -// using FilterState = ...; -// -// using Arc = typename FST1::Arc; -// using StateId = typename Arc::StateId; -// using Weight = typename Arc::Weight; -// -// // Required constructor. -// ComposeFilter(const FST1 &fst1, const FST2 &fst2, -// M1 *matcher1 = nullptr, M2 *matcher2 = nullptr); -// -// // If safe=true, the copy is thread-safe. See Fst<>::Copy() -// // for further doc. -// ComposeFilter(const ComposeFilter &filter, -// bool safe = false); -// -// // Return start state of filter. -// FilterState Start() const; -// -// // Specifies current composition state. -// void SetState(StateId s1, StateId s2, const FilterState &fs); -// -// // Apply filter at current composition state to these transitions. If an -// // arc label to be matched is kNolabel, then that side does not consume a -// // symbol. Returns the new filter state or, if disallowed, -// // FilterState::NoState(). The filter is permitted to modify its inputs -// // (e.g. for optimization reasons). -// FilterState FilterArc(Arc *arc1, Arc *arc2) const; - -// // Apply filter at current composition state to these final weights -// // (cf. superfinal transitions). The filter may modify its inputs -// // (e.g. for optimization reasons). -// void FilterFinal(Weight *w1, Weight *w2) const; -// -// // Return the respective matchers. Ownership stays with filter. These -// // methods allow the filter to access and possibly modify the compositio -// // matchers (useful, e.g., with lookahead). -// -// Matcher1 *GetMatcher1(); -// -// Matcher2 *GetMatcher2(); -// -// // This specifies how the filter affects the composition result properties. -// It takes as argument the properties that would apply with a trivial -// // composition filter. -// uint64_t Properties(uint64_t props) const; -// }; -// -// This filter allows only exact matching of symbols from FST1 with on FST2; -// e.g., no special interpretation of epsilons. -template -class NullComposeFilter { - public: - using Matcher1 = M1; - using Matcher2 = M2; - using FST1 = typename M1::FST; - using FST2 = typename M2::FST; - using FilterState = TrivialFilterState; - - using Arc = typename FST1::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - NullComposeFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, Matcher2 *matcher2 = nullptr) - : matcher1_(matcher1 ? matcher1 : new Matcher1(fst1, MATCH_OUTPUT)), - matcher2_(matcher2 ? matcher2 : new Matcher2(fst2, MATCH_INPUT)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()) {} - - NullComposeFilter(const NullComposeFilter &filter, bool safe = false) - : matcher1_(filter.matcher1_->Copy(safe)), - matcher2_(filter.matcher2_->Copy(safe)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()) {} - - FilterState Start() const { return FilterState(true); } - - void SetState(StateId, StateId, const FilterState &) {} - - FilterState FilterArc(Arc *arc1, Arc *arc2) const { - return (arc1->olabel == kNoLabel || arc2->ilabel == kNoLabel) - ? FilterState::NoState() - : FilterState(true); - } - - void FilterFinal(Weight *, Weight *) const {} - - Matcher1 *GetMatcher1() { return matcher1_.get(); } - - Matcher2 *GetMatcher2() { return matcher2_.get(); } - - uint64_t Properties(uint64_t props) const { return props; } - - private: - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - const FST1 &fst1_; - const FST2 &fst2_; -}; - -// This filter allows all epsilon matches, potentially resulting in redundant -// epsilon paths. The use of this filter gives correct results iff one of the -// following conditions hold: -// -// (1) The semiring is idempotent, -// (2) the first FST is output-epsilon free, or -// (3) the second FST is input-epsilon free. -// -// For (1), redundant epsilon paths may be created but won't hurt correctness. -// For (2) and (3), no redundant paths are created. -template -class TrivialComposeFilter { - public: - using Matcher1 = M1; - using Matcher2 = M2; - using FST1 = typename M1::FST; - using FST2 = typename M2::FST; - using FilterState = TrivialFilterState; - - using Arc = typename FST1::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - TrivialComposeFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, - Matcher2 *matcher2 = nullptr) - : matcher1_(matcher1 ? matcher1 : new Matcher1(fst1, MATCH_OUTPUT)), - matcher2_(matcher2 ? matcher2 : new Matcher2(fst2, MATCH_INPUT)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()) {} - - TrivialComposeFilter(const TrivialComposeFilter &filter, - bool safe = false) - : matcher1_(filter.matcher1_->Copy(safe)), - matcher2_(filter.matcher2_->Copy(safe)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()) {} - - FilterState Start() const { return FilterState(true); } - - void SetState(StateId, StateId, const FilterState &) {} - - FilterState FilterArc(Arc *, Arc *) const { return FilterState(true); } - - void FilterFinal(Weight *, Weight *) const {} - - Matcher1 *GetMatcher1() { return matcher1_.get(); } - - Matcher2 *GetMatcher2() { return matcher2_.get(); } - - uint64_t Properties(uint64_t props) const { return props; } - - private: - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - const FST1 &fst1_; - const FST2 &fst2_; -}; - -// This filter requires epsilons on FST1 to be read before epsilons on FST2. -template -class SequenceComposeFilter { - public: - using Matcher1 = M1; - using Matcher2 = M2; - using FST1 = typename M1::FST; - using FST2 = typename M2::FST; - using FilterState = CharFilterState; - - using Arc = typename FST1::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - SequenceComposeFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, - Matcher2 *matcher2 = nullptr) - : matcher1_(matcher1 ? matcher1 : new Matcher1(fst1, MATCH_OUTPUT)), - matcher2_(matcher2 ? matcher2 : new Matcher2(fst2, MATCH_INPUT)), - fst1_(matcher1_->GetFst()), - s1_(kNoStateId), - s2_(kNoStateId), - fs_(kNoStateId) {} - - SequenceComposeFilter(const SequenceComposeFilter &filter, - bool safe = false) - : matcher1_(filter.matcher1_->Copy(safe)), - matcher2_(filter.matcher2_->Copy(safe)), - fst1_(matcher1_->GetFst()), - s1_(kNoStateId), - s2_(kNoStateId), - fs_(kNoStateId) {} - - FilterState Start() const { return FilterState(0); } - - void SetState(StateId s1, StateId s2, const FilterState &fs) { - if (s1_ == s1 && s2_ == s2 && fs == fs_) return; - s1_ = s1; - s2_ = s2; - fs_ = fs; - const auto na1 = internal::NumArcs(fst1_, s1); - const auto ne1 = internal::NumOutputEpsilons(fst1_, s1); - const bool fin1 = internal::Final(fst1_, s1) != Weight::Zero(); - alleps1_ = na1 == ne1 && !fin1; - noeps1_ = ne1 == 0; - } - - FilterState FilterArc(Arc *arc1, Arc *arc2) const { - if (arc1->olabel == kNoLabel) { - return alleps1_ ? FilterState::NoState() - : noeps1_ ? FilterState(0) - : FilterState(1); - } else if (arc2->ilabel == kNoLabel) { - return fs_ != FilterState(0) ? FilterState::NoState() : FilterState(0); - } else { - return arc1->olabel == 0 ? FilterState::NoState() : FilterState(0); - } - } - - void FilterFinal(Weight *, Weight *) const {} - - Matcher1 *GetMatcher1() { return matcher1_.get(); } - - Matcher2 *GetMatcher2() { return matcher2_.get(); } - - uint64_t Properties(uint64_t props) const { return props; } - - private: - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - const FST1 &fst1_; - StateId s1_; // Current fst1_ state. - StateId s2_; // Current fst2_ state. - FilterState fs_; // Current filter state. - bool alleps1_; // Only epsilons (and non-final) leaving s1_? - bool noeps1_; // No epsilons leaving s1_? -}; - -// This filter requires epsilons on FST2 to be read before epsilons on FST1. -template -class AltSequenceComposeFilter { - public: - using Matcher1 = M1; - using Matcher2 = M2; - using FST1 = typename M1::FST; - using FST2 = typename M2::FST; - using FilterState = CharFilterState; - - using Arc = typename FST1::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - AltSequenceComposeFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, - Matcher2 *matcher2 = nullptr) - : matcher1_(matcher1 ? matcher1 : new Matcher1(fst1, MATCH_OUTPUT)), - matcher2_(matcher2 ? matcher2 : new Matcher2(fst2, MATCH_INPUT)), - fst2_(matcher2_->GetFst()), - s1_(kNoStateId), - s2_(kNoStateId), - fs_(kNoStateId) {} - - AltSequenceComposeFilter( - const AltSequenceComposeFilter &filter, - bool safe = false) - : matcher1_(filter.matcher1_->Copy(safe)), - matcher2_(filter.matcher2_->Copy(safe)), - fst2_(matcher2_->GetFst()), - s1_(kNoStateId), - s2_(kNoStateId), - fs_(kNoStateId) {} - - FilterState Start() const { return FilterState(0); } - - void SetState(StateId s1, StateId s2, const FilterState &fs) { - if (s1_ == s1 && s2_ == s2 && fs == fs_) return; - s1_ = s1; - s2_ = s2; - fs_ = fs; - const auto na2 = internal::NumArcs(fst2_, s2); - const auto ne2 = internal::NumInputEpsilons(fst2_, s2); - const bool fin2 = internal::Final(fst2_, s2) != Weight::Zero(); - alleps2_ = na2 == ne2 && !fin2; - noeps2_ = ne2 == 0; - } - - FilterState FilterArc(Arc *arc1, Arc *arc2) const { - if (arc2->ilabel == kNoLabel) { - return alleps2_ ? FilterState::NoState() - : noeps2_ ? FilterState(0) - : FilterState(1); - } else if (arc1->olabel == kNoLabel) { - return fs_ == FilterState(1) ? FilterState::NoState() : FilterState(0); - } else { - return arc1->olabel == 0 ? FilterState::NoState() : FilterState(0); - } - } - - void FilterFinal(Weight *, Weight *) const {} - - Matcher1 *GetMatcher1() { return matcher1_.get(); } - - Matcher2 *GetMatcher2() { return matcher2_.get(); } - - uint64_t Properties(uint64_t props) const { return props; } - - private: - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - const FST2 &fst2_; - StateId s1_; // Current fst1_ state. - StateId s2_; // Current fst2_ state. - FilterState fs_; // Current filter state. - bool alleps2_; // Only epsilons (and non-final) leaving s2_? - bool noeps2_; // No epsilons leaving s2_? -}; - -// This filter requires epsilons on FST1 to be matched with epsilons on FST2 -// whenever possible. (Template arg default declared in fst-decl.h.) -template -class MatchComposeFilter { - public: - using Matcher1 = M1; - using Matcher2 = M2; - using FST1 = typename M1::FST; - using FST2 = typename M2::FST; - using FilterState = CharFilterState; - - using Arc = typename FST1::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - MatchComposeFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, Matcher2 *matcher2 = nullptr) - : matcher1_(matcher1 ? matcher1 : new Matcher1(fst1, MATCH_OUTPUT)), - matcher2_(matcher2 ? matcher2 : new Matcher2(fst2, MATCH_INPUT)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()), - s1_(kNoStateId), - s2_(kNoStateId), - fs_(kNoStateId) {} - - MatchComposeFilter(const MatchComposeFilter &filter, - bool safe = false) - : matcher1_(filter.matcher1_->Copy(safe)), - matcher2_(filter.matcher2_->Copy(safe)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()), - s1_(kNoStateId), - s2_(kNoStateId), - fs_(kNoStateId) {} - - FilterState Start() const { return FilterState(0); } - - void SetState(StateId s1, StateId s2, const FilterState &fs) { - if (s1_ == s1 && s2_ == s2 && fs == fs_) return; - s1_ = s1; - s2_ = s2; - fs_ = fs; - size_t na1 = internal::NumArcs(fst1_, s1); - size_t ne1 = internal::NumOutputEpsilons(fst1_, s1); - bool f1 = internal::Final(fst1_, s1) != Weight::Zero(); - alleps1_ = na1 == ne1 && !f1; - noeps1_ = ne1 == 0; - size_t na2 = internal::NumArcs(fst2_, s2); - size_t ne2 = internal::NumInputEpsilons(fst2_, s2); - bool f2 = internal::Final(fst2_, s2) != Weight::Zero(); - alleps2_ = na2 == ne2 && !f2; - noeps2_ = ne2 == 0; - } - - FilterState FilterArc(Arc *arc1, Arc *arc2) const { - if (arc2->ilabel == kNoLabel) { // Epsilon in FST1. - return fs_ == FilterState(0) - ? (noeps2_ - ? FilterState(0) - : (alleps2_ ? FilterState::NoState() : FilterState(1))) - : (fs_ == FilterState(1) ? FilterState(1) - : FilterState::NoState()); - } else if (arc1->olabel == kNoLabel) { // Epsilon in FST2. - return fs_ == FilterState(0) - ? (noeps1_ - ? FilterState(0) - : (alleps1_ ? FilterState::NoState() : FilterState(2))) - : (fs_ == FilterState(2) ? FilterState(2) - : FilterState::NoState()); - } else if (arc1->olabel == 0) { // Epsilon in both. - return fs_ == FilterState(0) ? FilterState(0) : FilterState::NoState(); - } else { // Both are non-epsilons. - return FilterState(0); - } - } - - void FilterFinal(Weight *, Weight *) const {} - - Matcher1 *GetMatcher1() { return matcher1_.get(); } - - Matcher2 *GetMatcher2() { return matcher2_.get(); } - - uint64_t Properties(uint64_t props) const { return props; } - - private: - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - const FST1 &fst1_; - const FST2 &fst2_; - StateId s1_; // Current fst1_ state. - StateId s2_; // Current fst2_ state. - FilterState fs_; // Current filter state ID. - bool alleps1_; // Only epsilson (and non-final) leaving s1? - bool alleps2_; // Only epsilons (and non-final) leaving s2? - bool noeps1_; // No epsilons leaving s1? - bool noeps2_; // No epsilons leaving s2? -}; - -// This filter disallows matching epsilons on FST1 with epsilons on FST2, -// but allows all other matches, potentially resulting in redundant -// epsilon paths. The use of this filter gives correct results iff one of the -// following conditions hold: -// -// (1) The semiring is idempotent, -// (2) the first FST is output-epsilon free, or -// (3) the second FST is input-epsilon free. -// -// For (1), redundant epsilon paths may be created but won't hurt correctness. -// For (2) and (3), no redundant paths are created. -template -class NoMatchComposeFilter { - public: - using Matcher1 = M1; - using Matcher2 = M2; - using FST1 = typename M1::FST; - using FST2 = typename M2::FST; - using FilterState = TrivialFilterState; - - using Arc = typename FST1::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - NoMatchComposeFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, - Matcher2 *matcher2 = nullptr) - : matcher1_(matcher1 ? matcher1 : new Matcher1(fst1, MATCH_OUTPUT)), - matcher2_(matcher2 ? matcher2 : new Matcher2(fst2, MATCH_INPUT)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()) {} - - NoMatchComposeFilter(const NoMatchComposeFilter &filter, - bool safe = false) - : matcher1_(filter.matcher1_->Copy(safe)), - matcher2_(filter.matcher2_->Copy(safe)), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()) {} - - FilterState Start() const { return FilterState(true); } - - void SetState(StateId, StateId, const FilterState &) {} - - FilterState FilterArc(Arc *arc1, Arc *arc2) const { - return FilterState(arc1->olabel != 0 || arc2->ilabel != 0); - } - - void FilterFinal(Weight *, Weight *) const {} - - Matcher1 *GetMatcher1() { return matcher1_.get(); } - - Matcher2 *GetMatcher2() { return matcher2_.get(); } - - uint64_t Properties(uint64_t props) const { return props; } - - private: - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - const FST1 &fst1_; - const FST2 &fst2_; -}; - -// This filter works with the MultiEpsMatcher to determine if multi-epsilons are -// preserved in the composition output (rather than rewritten as 0) and -// ensures correct properties. -template -class MultiEpsFilter { - public: - using Matcher1 = typename Filter::Matcher1; - using Matcher2 = typename Filter::Matcher2; - using FST1 = typename Filter::FST1; - using FST2 = typename Filter::FST2; - using FilterState = typename Filter::FilterState; - - using Arc = typename Filter::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - MultiEpsFilter(const FST1 &fst1, const FST2 &fst2, - Matcher1 *matcher1 = nullptr, Matcher2 *matcher2 = nullptr, - bool keep_multi_eps = false) - : filter_(fst1, fst2, matcher1, matcher2), - keep_multi_eps_(keep_multi_eps) {} - - MultiEpsFilter(const MultiEpsFilter &filter, bool safe = false) - : filter_(filter.filter_, safe), - keep_multi_eps_(filter.keep_multi_eps_) {} - - FilterState Start() const { return filter_.Start(); } - - void SetState(StateId s1, StateId s2, const FilterState &fs) { - return filter_.SetState(s1, s2, fs); - } - - FilterState FilterArc(Arc *arc1, Arc *arc2) const { - const auto fs = filter_.FilterArc(arc1, arc2); - if (keep_multi_eps_) { - if (arc1->olabel == kNoLabel) arc1->ilabel = arc2->ilabel; - if (arc2->ilabel == kNoLabel) arc2->olabel = arc1->olabel; - } - return fs; - } - - void FilterFinal(Weight *w1, Weight *w2) const { - return filter_.FilterFinal(w1, w2); - } - - Matcher1 *GetMatcher1() { return filter_.GetMatcher1(); } - - Matcher2 *GetMatcher2() { return filter_.GetMatcher2(); } - - uint64_t Properties(uint64_t iprops) const { - const auto oprops = filter_.Properties(iprops); - return oprops & kILabelInvariantProperties & kOLabelInvariantProperties; - } - - private: - Filter filter_; - bool keep_multi_eps_; -}; - -} // namespace fst - -#endif // FST_COMPOSE_FILTER_H_ diff --git a/contrib/fstlib/fst/compose.h b/contrib/fstlib/fst/compose.h deleted file mode 100644 index db0b03b..0000000 --- a/contrib/fstlib/fst/compose.h +++ /dev/null @@ -1,1059 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to compute the composition of two FSTs. - -#ifndef FST_COMPOSE_H_ -#define FST_COMPOSE_H_ - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include // For optional argument declarations -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Delayed composition options templated on the arc type, the matcher, -// the composition filter, and the composition state table. By -// default, the matchers, filter, and state table are constructed by -// composition. If set below, the user can instead pass in these -// objects; in that case, ComposeFst takes their ownership. This -// version controls composition implemented between generic Fst -// types and a shared matcher type M for Fst. This should be -// adequate for most applications, giving a reasonable tradeoff -// between efficiency and code sharing (but see ComposeFstImplOptions). -template >, - class Filter = SequenceComposeFilter, - class StateTable = - GenericComposeStateTable> -struct ComposeFstOptions : public CacheOptions { - M *matcher1; // FST1 matcher. - M *matcher2; // FST2 matcher. - Filter *filter; // Composition filter. - StateTable *state_table; // Composition state table. - - explicit ComposeFstOptions(const CacheOptions &opts = CacheOptions(), - M *matcher1 = nullptr, M *matcher2 = nullptr, - Filter *filter = nullptr, - StateTable *state_table = nullptr) - : CacheOptions(opts), - matcher1(matcher1), - matcher2(matcher2), - filter(filter), - state_table(state_table) {} -}; - -// Forward declaration of ComposeFstMatcher. -template -class ComposeFstMatcher; - -// Delayed composition options templated on the two matcher types, the -// composition filter, the composition state table and the cache store. By -// default, the matchers, filter, state table and cache store are constructed -// by composition. If set below, the user can instead pass in these objects; in -// that case, ComposeFst takes their ownership. This version controls -// composition implemented using arbitrary matchers (of the same arc type but -// otherwise arbitrary FST type). The user must ensure the matchers are -// compatible. These options permit the most efficient use, but shares the -// least code. This is for advanced use only in the most demanding or -// specialized applications that can benefit from it; otherwise, prefer -// ComposeFstOptions). -template , - class StateTable = GenericComposeStateTable< - typename M1::Arc, typename Filter::FilterState>, - class CacheStore = DefaultCacheStore> -struct ComposeFstImplOptions : public CacheImplOptions { - M1 *matcher1; // FST1 matcher (see matcher.h).... - M2 *matcher2; // FST2 matcher. - Filter *filter; // Composition filter (see compose-filter.h). - StateTable - *state_table; // Composition state table (see compose-state-table.h). - bool own_state_table; // ComposeFstImpl takes ownership of 'state_table'? - bool allow_noncommute; // Allow non-commutative weights - - explicit ComposeFstImplOptions(const CacheOptions &opts, - M1 *matcher1 = nullptr, M2 *matcher2 = nullptr, - Filter *filter = nullptr, - StateTable *state_table = nullptr) - : CacheImplOptions(opts), - matcher1(matcher1), - matcher2(matcher2), - filter(filter), - state_table(state_table), - own_state_table(true), - allow_noncommute(false) {} - - explicit ComposeFstImplOptions(const CacheImplOptions &opts, - M1 *matcher1 = nullptr, M2 *matcher2 = nullptr, - Filter *filter = nullptr, - StateTable *state_table = nullptr) - : CacheImplOptions(opts), - matcher1(matcher1), - matcher2(matcher2), - filter(filter), - state_table(state_table), - own_state_table(true), - allow_noncommute(false) {} - - ComposeFstImplOptions() - : matcher1(nullptr), - matcher2(nullptr), - filter(nullptr), - state_table(nullptr), - own_state_table(true), - allow_noncommute(false) {} -}; - -namespace internal { - -// Implementation of delayed composition. This base class is common to the -// variants with different matchers, composition filters and state tables. -template , - class F = ComposeFst> -class ComposeFstImplBase - : public CacheBaseImpl { - public: - using FST = F; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using State = typename CacheStore::State; - using CacheImpl = CacheBaseImpl; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::Properties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheImpl::HasArcs; - using CacheImpl::HasFinal; - using CacheImpl::HasStart; - using CacheImpl::SetFinal; - using CacheImpl::SetStart; - - explicit ComposeFstImplBase(const CacheImplOptions &opts) - : CacheImpl(opts) {} - - explicit ComposeFstImplBase(const CacheOptions &opts) : CacheImpl(opts) {} - - ComposeFstImplBase(const ComposeFstImplBase &impl) : CacheImpl(impl, true) { - SetType(impl.Type()); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - virtual ComposeFstImplBase *Copy() const = 0; - - ~ComposeFstImplBase() override = default; - - StateId Start() { - if (!HasStart()) { - const auto start = ComputeStart(); - if (start != kNoStateId) SetStart(start); - } - return CacheImpl::Start(); - } - - Weight Final(StateId s) { - if (!HasFinal(s)) SetFinal(s, ComputeFinal(s)); - return CacheImpl::Final(s); - } - - virtual void Expand(StateId s) = 0; - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - virtual MatcherBase *InitMatcher(const F &fst, - MatchType match_type) const { - // Use the default matcher if no override is provided. - return nullptr; - } - - protected: - virtual StateId ComputeStart() = 0; - virtual Weight ComputeFinal(StateId s) = 0; -}; - -// Implementation of delayed composition templated on the matchers (see -// matcher.h), composition filter (see compose-filter.h) and the composition -// state table (see compose-state-table.h). -template -class ComposeFstImpl - : public ComposeFstImplBase { - public: - using Matcher1 = typename Filter::Matcher1; - using Matcher2 = typename Filter::Matcher2; - - using FST1 = typename Matcher1::FST; - using FST2 = typename Matcher2::FST; - - using Arc = typename CacheStore::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FilterState = typename Filter::FilterState; - using State = typename CacheStore::State; - - using CacheImpl = CacheBaseImpl; - - using StateTuple = typename StateTable::StateTuple; - - friend class ComposeFstMatcher; - - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - using FstImpl::SetType; - using FstImpl::SetProperties; - - template - ComposeFstImpl(const FST1 &fst1, const FST2 &fst2, - const ComposeFstImplOptions &opts); - - ComposeFstImpl(const ComposeFstImpl &impl) - : ComposeFstImplBase(impl), - filter_(new Filter(*impl.filter_, true)), - matcher1_(filter_->GetMatcher1()), - matcher2_(filter_->GetMatcher2()), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()), - state_table_(new StateTable(*impl.state_table_)), - own_state_table_(true), - match_type_(impl.match_type_) {} - - ~ComposeFstImpl() override { - if (own_state_table_) delete state_table_; - } - - ComposeFstImpl *Copy() const override { return new ComposeFstImpl(*this); } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && - (fst1_.Properties(kError, false) || fst2_.Properties(kError, false) || - (matcher1_->Properties(0) & kError) || - (matcher2_->Properties(0) & kError) | - (filter_->Properties(0) & kError) || - state_table_->Error())) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - // Arranges it so that the first arg to OrderedExpand is the Fst - // that will be matched on. - void Expand(StateId s) override { - const auto &tuple = state_table_->Tuple(s); - const auto s1 = tuple.StateId1(); - const auto s2 = tuple.StateId2(); - filter_->SetState(s1, s2, tuple.GetFilterState()); - if (MatchInput(s1, s2)) { - OrderedExpand(s, fst2_, s2, fst1_, s1, matcher2_, true); - } else { - OrderedExpand(s, fst1_, s1, fst2_, s2, matcher1_, false); - } - } - - const FST1 &GetFst1() const { return fst1_; } - - const FST2 &GetFst2() const { return fst2_; } - - const Matcher1 *GetMatcher1() const { return matcher1_; } - - Matcher1 *GetMatcher1() { return matcher1_; } - - const Matcher2 *GetMatcher2() const { return matcher2_; } - - Matcher2 *GetMatcher2() { return matcher2_; } - - const Filter *GetFilter() const { return filter_.get(); } - - Filter *GetFilter() { return filter_.get(); } - - const StateTable *GetStateTable() const { return state_table_; } - - StateTable *GetStateTable() { return state_table_; } - - MatcherBase *InitMatcher(const ComposeFst &fst, - MatchType match_type) const override { - const auto test_props = match_type == MATCH_INPUT - ? kFstProperties & ~kILabelInvariantProperties - : kFstProperties & ~kOLabelInvariantProperties; - // If both matchers support 'match_type' and we have a guarantee that a - // call to 'filter_->FilterArc(arc1, arc2)' will not modify the ilabel of - // arc1 when MATCH_INPUT or the olabel or arc2 when MATCH_OUTPUT, then - // ComposeFstMatcher can be used. - if ((matcher1_->Type(false) == match_type) && - (matcher2_->Type(false) == match_type) && - (filter_->Properties(test_props) == test_props)) { - return new ComposeFstMatcher(&fst, - match_type); - } - return nullptr; - } - - private: - // This does that actual matching of labels in the composition. The - // arguments are ordered so matching is called on state 'sa' of - // 'fsta' for each arc leaving state 'sb' of 'fstb'. The 'match_input' arg - // determines whether the input or output label of arcs at 'sb' is - // the one to match on. - template - void OrderedExpand(StateId s, const Fst &, StateId sa, const FST &fstb, - StateId sb, Matcher *matchera, bool match_input) { - matchera->SetState(sa); - // First processes non-consuming symbols (e.g., epsilons) on FSTA. - const Arc loop(match_input ? 0 : kNoLabel, match_input ? kNoLabel : 0, - Weight::One(), sb); - MatchArc(s, matchera, loop, match_input); - // Then processes matches on FSTB. - for (ArcIterator iterb(fstb, sb); !iterb.Done(); iterb.Next()) { - MatchArc(s, matchera, iterb.Value(), match_input); - } - CacheImpl::SetArcs(s); - } - - // Matches a single transition from 'fstb' against 'fata' at 's'. - template - void MatchArc(StateId s, Matcher *matchera, const Arc &arc, - bool match_input) { - if (matchera->Find(match_input ? arc.olabel : arc.ilabel)) { - for (; !matchera->Done(); matchera->Next()) { - auto arca = matchera->Value(); - auto arcb = arc; - if (match_input) { - const auto &fs = filter_->FilterArc(&arcb, &arca); - if (fs != FilterState::NoState()) AddArc(s, arcb, arca, fs); - } else { - const auto &fs = filter_->FilterArc(&arca, &arcb); - if (fs != FilterState::NoState()) AddArc(s, arca, arcb, fs); - } - } - } - } - - // Add a matching transition at 's'. - void AddArc(StateId s, const Arc &arc1, const Arc &arc2, - const FilterState &f) { - const StateTuple tuple(arc1.nextstate, arc2.nextstate, f); - CacheImpl::EmplaceArc(s, arc1.ilabel, arc2.olabel, - Times(arc1.weight, arc2.weight), - state_table_->FindState(tuple)); - } - - StateId ComputeStart() override { - const auto s1 = fst1_.Start(); - if (s1 == kNoStateId) return kNoStateId; - const auto s2 = fst2_.Start(); - if (s2 == kNoStateId) return kNoStateId; - const auto &fs = filter_->Start(); - const StateTuple tuple(s1, s2, fs); - return state_table_->FindState(tuple); - } - - Weight ComputeFinal(StateId s) override { - const auto &tuple = state_table_->Tuple(s); - const auto s1 = tuple.StateId1(); - auto final1 = matcher1_->Final(s1); - if (final1 == Weight::Zero()) return final1; - const auto s2 = tuple.StateId2(); - auto final2 = matcher2_->Final(s2); - if (final2 == Weight::Zero()) return final2; - filter_->SetState(s1, s2, tuple.GetFilterState()); - filter_->FilterFinal(&final1, &final2); - return Times(final1, final2); - } - - // Determines which side to match on per composition state. - bool MatchInput(StateId s1, StateId s2) { - switch (match_type_) { - case MATCH_INPUT: - return true; - case MATCH_OUTPUT: - return false; - default: // MATCH_BOTH - const auto priority1 = matcher1_->Priority(s1); - const auto priority2 = matcher2_->Priority(s2); - if (priority1 == kRequirePriority && priority2 == kRequirePriority) { - FSTERROR() << "ComposeFst: Both sides can't require match"; - SetProperties(kError, kError); - return true; - } - if (priority1 == kRequirePriority) return false; - if (priority2 == kRequirePriority) { - return true; - } - return priority1 <= priority2; - } - } - - // Identifies and verifies the capabilities of the matcher to be used for - // composition. - void SetMatchType(); - - std::unique_ptr filter_; - Matcher1 *matcher1_; // Borrowed reference. - Matcher2 *matcher2_; // Borrowed reference. - const FST1 &fst1_; - const FST2 &fst2_; - StateTable *state_table_; - bool own_state_table_; - - MatchType match_type_; -}; - -template -template -ComposeFstImpl::ComposeFstImpl( - const FST1 &fst1, const FST2 &fst2, - const ComposeFstImplOptions &opts) - : ComposeFstImplBase(opts), - filter_(opts.filter - ? opts.filter - : new Filter(fst1, fst2, opts.matcher1, opts.matcher2)), - matcher1_(filter_->GetMatcher1()), - matcher2_(filter_->GetMatcher2()), - fst1_(matcher1_->GetFst()), - fst2_(matcher2_->GetFst()), - state_table_(opts.state_table ? opts.state_table - : new StateTable(fst1_, fst2_)), - own_state_table_(opts.state_table ? opts.own_state_table : true) { - SetType("compose"); - if (!CompatSymbols(fst2.InputSymbols(), fst1.OutputSymbols())) { - FSTERROR() << "ComposeFst: Output symbol table of 1st argument " - << "does not match input symbol table of 2nd argument"; - SetProperties(kError, kError); - } - SetInputSymbols(fst1_.InputSymbols()); - SetOutputSymbols(fst2_.OutputSymbols()); - SetMatchType(); - VLOG(2) << "ComposeFstImpl: Match type: " << match_type_; - if (match_type_ == MATCH_NONE) SetProperties(kError, kError); - const auto fprops1 = fst1.Properties(kFstProperties, false); - const auto fprops2 = fst2.Properties(kFstProperties, false); - const auto mprops1 = matcher1_->Properties(fprops1); - const auto mprops2 = matcher2_->Properties(fprops2); - const auto cprops = ComposeProperties(mprops1, mprops2); - SetProperties(filter_->Properties(cprops), kCopyProperties); - if (state_table_->Error()) SetProperties(kError, kError); -} - -template -void ComposeFstImpl::SetMatchType() { - // Ensures any required matching is possible and known. - if ((matcher1_->Flags() & kRequireMatch) && - matcher1_->Type(true) != MATCH_OUTPUT) { - FSTERROR() << "ComposeFst: 1st argument cannot perform required matching " - << "(sort?)."; - match_type_ = MATCH_NONE; - return; - } - if ((matcher2_->Flags() & kRequireMatch) && - matcher2_->Type(true) != MATCH_INPUT) { - FSTERROR() << "ComposeFst: 2nd argument cannot perform required matching " - << "(sort?)."; - match_type_ = MATCH_NONE; - return; - } - // Finds which sides to match on (favoring minimal testing of capabilities). - const auto type1 = matcher1_->Type(false); - const auto type2 = matcher2_->Type(false); - if (type1 == MATCH_OUTPUT && type2 == MATCH_INPUT) { - match_type_ = MATCH_BOTH; - } else if (type1 == MATCH_OUTPUT) { - match_type_ = MATCH_OUTPUT; - } else if (type2 == MATCH_INPUT) { - match_type_ = MATCH_INPUT; - } else if (matcher1_->Type(true) == MATCH_OUTPUT) { - match_type_ = MATCH_OUTPUT; - } else if (matcher2_->Type(true) == MATCH_INPUT) { - match_type_ = MATCH_INPUT; - } else { - FSTERROR() << "ComposeFst: 1st argument cannot match on output labels " - << "and 2nd argument cannot match on input labels (sort?)."; - match_type_ = MATCH_NONE; - } -} - -} // namespace internal - -// Computes the composition of two transducers. This version is a delayed FST. -// If FST1 transduces string x to y with weight a and FST2 transduces y to z -// with weight b, then their composition transduces string x to z with weight -// Times(x, z). -// -// The output labels of the first transducer or the input labels of the second -// transducer must be sorted (with the default matcher). The weights need to -// form a commutative semiring (valid for TropicalWeight and LogWeight). -// -// Complexity: -// -// Assuming the first FST is unsorted and the second is sorted, -// -// Time: O(v1 v2 d1 (log d2 + m2)), -// Space: O(v1 v2) -// -// where vi = # of states visited, di = maximum out-degree, and mi the -// maximum multiplicity of the states visited, for the ith FST. Constant time -// and space to visit an input state or arc is assumed and exclusive of caching. -// -// Caveats: -// - ComposeFst does not trim its output (since it is a delayed operation). -// - The efficiency of composition can be strongly affected by several factors: -// - the choice of which transducer is sorted - prefer sorting the FST -// that has the greater average out-degree. -// - the amount of non-determinism -// - the presence and location of epsilon transitions - avoid epsilon -// transitions on the output side of the first transducer or -// the input side of the second transducer or prefer placing -// them later in a path since they delay matching and can -// introduce non-coaccessible states and transitions. -// -// This class attaches interface to implementation and handles reference -// counting, delegating most methods to ImplToFst. The CacheStore specifies the -// cache store (default declared in fst-decl.h). -template */> -class ComposeFst - : public ImplToFst> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = CacheStore; - using State = typename CacheStore::State; - - using Impl = internal::ComposeFstImplBase; - - friend class ArcIterator>; - friend class StateIterator>; - template - friend class ComposeFstMatcher; - - // Compose specifying only caching options. - ComposeFst(const Fst &fst1, const Fst &fst2, - const CacheOptions &opts = CacheOptions()) - : ImplToFst(CreateBase(fst1, fst2, opts)) {} - - // Compose specifying one shared matcher type M. Requires that the input FSTs - // and matcher FST types be Fst. Recommended for best code-sharing and - // matcher compatibility. - template - ComposeFst(const Fst &fst1, const Fst &fst2, - const ComposeFstOptions &opts) - : ImplToFst(CreateBase1(fst1, fst2, opts)) {} - - // Compose specifying two matcher types Matcher1 and Matcher2. Requires input - // FST (of the same Arc type, but o.w. arbitrary) match the corresponding - // matcher FST types). Recommended only for advanced use in demanding or - // specialized applications due to potential code bloat and matcher - // incompatibilities. - template - ComposeFst(const typename Matcher1::FST &fst1, - const typename Matcher2::FST &fst2, - const ComposeFstImplOptions &opts) - : ImplToFst(CreateBase2(fst1, fst2, opts)) {} - - // See Fst<>::Copy() for doc. - ComposeFst(const ComposeFst &fst, bool safe = false) - : ImplToFst(safe ? std::shared_ptr(fst.GetImpl()->Copy()) - : fst.GetSharedImpl()) {} - - // Get a copy of this ComposeFst. See Fst<>::Copy() for further doc. - ComposeFst *Copy(bool safe = false) const override { - return new ComposeFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - MatcherBase *InitMatcher(MatchType match_type) const override { - return GetImpl()->InitMatcher(*this, match_type); - } - - protected: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - explicit ComposeFst(std::shared_ptr impl) : ImplToFst(impl) {} - - // Create compose implementation specifying two matcher types. - template - static std::shared_ptr CreateBase2( - const typename Matcher1::FST &fst1, const typename Matcher2::FST &fst2, - const ComposeFstImplOptions &opts) { - auto impl = std::make_shared< - internal::ComposeFstImpl>(fst1, fst2, - opts); - if (!(Weight::Properties() & kCommutative) && !opts.allow_noncommute) { - const auto props1 = fst1.Properties(kUnweighted, true); - const auto props2 = fst2.Properties(kUnweighted, true); - if (!(props1 & kUnweighted) && !(props2 & kUnweighted)) { - FSTERROR() << "ComposeFst: Weights must be a commutative semiring: " - << Weight::Type(); - impl->SetProperties(kError, kError); - } - } - return impl; - } - - // Create compose implementation specifying one matcher type; requires that - // input and matcher FST types be Fst. - template - static std::shared_ptr CreateBase1( - const Fst &fst1, const Fst &fst2, - const ComposeFstOptions &opts) { - ComposeFstImplOptions - nopts(opts, opts.matcher1, opts.matcher2, opts.filter, - opts.state_table); - return CreateBase2(fst1, fst2, nopts); - } - - // Create compose implementation specifying no matcher type. - static std::shared_ptr CreateBase(const Fst &fst1, - const Fst &fst2, - const CacheOptions &opts) { - switch (LookAheadMatchType(fst1, fst2)) { // Check for lookahead matchers - default: - case MATCH_NONE: { // Default composition (no look-ahead). - ComposeFstOptions nopts(opts); - return CreateBase1(fst1, fst2, nopts); - } - case MATCH_OUTPUT: { // Lookahead on fst1. - using M = typename DefaultLookAhead::FstMatcher; - using F = typename DefaultLookAhead::ComposeFilter; - ComposeFstOptions nopts(opts); - return CreateBase1(fst1, fst2, nopts); - } - case MATCH_INPUT: { // Lookahead on fst2 - using M = typename DefaultLookAhead::FstMatcher; - using F = typename DefaultLookAhead::ComposeFilter; - ComposeFstOptions nopts(opts); - return CreateBase1(fst1, fst2, nopts); - } - } - } - - private: - ComposeFst &operator=(const ComposeFst &fst) = delete; -}; - -// Specialization for ComposeFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const ComposeFst &fst) - : CacheStateIterator>(fst, - fst.GetMutableImpl()) {} -}; - -// Specialization for ComposeFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const ComposeFst &fst, StateId s) - : CacheArcIterator>(fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void ComposeFst::InitStateIterator( - StateIteratorData *data) const { - data->base = - std::make_unique>>(*this); -} - -// Specialized matcher for ComposeFst. Supports MATCH_INPUT or MATCH_OUTPUT, -// iff the underlying matchers for the two FSTS being composed support -// MATCH_INPUT or MATCH_OUTPUT, respectively. -template -class ComposeFstMatcher : public MatcherBase { - public: - using Arc = typename CacheStore::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Matcher1 = typename Filter::Matcher1; - using Matcher2 = typename Filter::Matcher2; - using FilterState = typename Filter::FilterState; - - using StateTuple = typename StateTable::StateTuple; - using Impl = internal::ComposeFstImpl; - - // The compose FST arg must match the filter and state table types. - // This makes a copy of the FST. - ComposeFstMatcher(const ComposeFst &fst, - MatchType match_type) - : owned_fst_(fst.Copy()), - fst_(*owned_fst_), - impl_(down_cast(fst_.GetImpl())), - s_(kNoStateId), - match_type_(match_type), - matcher1_(impl_->matcher1_->Copy()), - matcher2_(impl_->matcher2_->Copy()), - current_loop_(false), - loop_(kNoLabel, 0, Weight::One(), kNoStateId) { - if (match_type_ == MATCH_OUTPUT) std::swap(loop_.ilabel, loop_.olabel); - } - - // The compose FST arg must match the filter and state table types. - // This doesn't copy the FST (although it may copy components). - ComposeFstMatcher(const ComposeFst *fst, - MatchType match_type) - : fst_(*fst), - impl_(down_cast(fst_.GetImpl())), - s_(kNoStateId), - match_type_(match_type), - matcher1_(impl_->matcher1_->Copy()), - matcher2_(impl_->matcher2_->Copy()), - current_loop_(false), - loop_(kNoLabel, 0, Weight::One(), kNoStateId) { - if (match_type_ == MATCH_OUTPUT) std::swap(loop_.ilabel, loop_.olabel); - } - - // This makes a copy of the FST. - ComposeFstMatcher( - const ComposeFstMatcher &matcher, - bool safe = false) - : owned_fst_(matcher.fst_.Copy(safe)), - fst_(*owned_fst_), - impl_(down_cast(fst_.GetImpl())), - s_(kNoStateId), - match_type_(matcher.match_type_), - matcher1_(matcher.matcher1_->Copy(safe)), - matcher2_(matcher.matcher2_->Copy(safe)), - current_loop_(false), - loop_(kNoLabel, 0, Weight::One(), kNoStateId) { - if (match_type_ == MATCH_OUTPUT) std::swap(loop_.ilabel, loop_.olabel); - } - - ComposeFstMatcher *Copy(bool safe = false) const override { - return new ComposeFstMatcher(*this, safe); - } - - MatchType Type(bool test) const override { - if ((matcher1_->Type(test) == MATCH_NONE) || - (matcher2_->Type(test) == MATCH_NONE)) { - return MATCH_NONE; - } - if (((matcher1_->Type(test) == MATCH_UNKNOWN) && - (matcher2_->Type(test) == MATCH_UNKNOWN)) || - ((matcher1_->Type(test) == MATCH_UNKNOWN) && - (matcher2_->Type(test) == match_type_)) || - ((matcher1_->Type(test) == match_type_) && - (matcher2_->Type(test) == MATCH_UNKNOWN))) { - return MATCH_UNKNOWN; - } - if ((matcher1_->Type(test) == match_type_) && - (matcher2_->Type(test) == match_type_)) { - return match_type_; - } - return MATCH_NONE; - } - - const Fst &GetFst() const override { return fst_; } - - uint64_t Properties(uint64_t inprops) const override { return inprops; } - - void SetState(StateId s) final { - if (s_ == s) return; - s_ = s; - const auto &tuple = impl_->state_table_->Tuple(s); - matcher1_->SetState(tuple.StateId1()); - matcher2_->SetState(tuple.StateId2()); - loop_.nextstate = s_; - } - - bool Find(Label label) final { - bool found = false; - current_loop_ = false; - if (label == 0) { - current_loop_ = true; - found = true; - } - if (match_type_ == MATCH_INPUT) { - found = found || FindLabel(label, matcher1_.get(), matcher2_.get()); - } else { // match_type_ == MATCH_OUTPUT - found = found || FindLabel(label, matcher2_.get(), matcher1_.get()); - } - return found; - } - - bool Done() const final { - return !current_loop_ && matcher1_->Done() && matcher2_->Done(); - } - - const Arc &Value() const final { return current_loop_ ? loop_ : arc_; } - - void Next() final { - if (current_loop_) { - current_loop_ = false; - } else if (match_type_ == MATCH_INPUT) { - FindNext(matcher1_.get(), matcher2_.get()); - } else { // match_type_ == MATCH_OUTPUT - FindNext(matcher2_.get(), matcher1_.get()); - } - } - - ssize_t Priority(StateId s) final { return fst_.NumArcs(s); } - - private: - // Processes a match with the filter and creates resulting arc. - bool MatchArc(StateId s, Arc *arc1, Arc *arc2) { - const auto &fs = impl_->filter_->FilterArc(arc1, arc2); - if (fs == FilterState::NoState()) return false; - const StateTuple tuple(arc1->nextstate, arc2->nextstate, fs); - arc_.ilabel = arc1->ilabel; - arc_.olabel = arc2->olabel; - arc_.weight = Times(arc1->weight, arc2->weight); - arc_.nextstate = impl_->state_table_->FindState(tuple); - return true; - } - - // Finds the first match allowed by the filter. - template - bool FindLabel(Label label, MatcherA *matchera, MatcherB *matcherb) { - if (matchera->Find(label)) { - matcherb->Find(match_type_ == MATCH_INPUT ? matchera->Value().olabel - : matchera->Value().ilabel); - return FindNext(matchera, matcherb); - } - return false; - } - - // Finds the next match allowed by the filter, returning true iff such a - // match is found. - template - bool FindNext(MatcherA *matchera, MatcherB *matcherb) { - // State when entering this function: - // 'matchera' is pointed to a match x, y for label x, and a match for y was - // requested on 'matcherb'. - while (!matchera->Done() || !matcherb->Done()) { - if (matcherb->Done()) { - // If no more matches for y on 'matcherb', moves forward on 'matchera' - // until a match x, y' is found such that there is a match for y' on - // 'matcherb'. - matchera->Next(); - while (!matchera->Done() && - !matcherb->Find(match_type_ == MATCH_INPUT - ? matchera->Value().olabel - : matchera->Value().ilabel)) { - matchera->Next(); - } - } - while (!matcherb->Done()) { - // 'matchera' is pointing to a match x, y' ('arca') and 'matcherb' is - // pointing to a match y', z' ('arcb'). If combining these two arcs is - // allowed by the filter (hence resulting in an arc x, z') return true. - // Position 'matcherb' on the next potential match for y' before - // returning. - auto arca = matchera->Value(); - auto arcb = matcherb->Value(); - // Position 'matcherb' on the next potential match for y'. - matcherb->Next(); - // Returns true If combining these two arcs is allowed by the filter - // (hence resulting in an arc x, z'); otherwise consider next match - // for y' on 'matcherb'. - if (match_type_ == MATCH_INPUT) { - if (MatchArc(s_, &arca, &arcb)) return true; - } else { - if (MatchArc(s_, &arcb, &arca)) return true; - } - } - } - // Both 'matchera' and 'matcherb' are done, no more match to analyse. - return false; - } - - std::unique_ptr> owned_fst_; - const ComposeFst &fst_; - const Impl *impl_; - StateId s_; - MatchType match_type_; - std::unique_ptr matcher1_; - std::unique_ptr matcher2_; - bool current_loop_; - Arc loop_; - Arc arc_; -}; - -// Useful alias when using StdArc. -using StdComposeFst = ComposeFst; - -enum ComposeFilter { - AUTO_FILTER, - NULL_FILTER, - TRIVIAL_FILTER, - SEQUENCE_FILTER, - ALT_SEQUENCE_FILTER, - MATCH_FILTER, - NO_MATCH_FILTER -}; - -struct ComposeOptions { - bool connect; // Connect output? - ComposeFilter filter_type; // Pre-defined filter to use. - - explicit ComposeOptions(bool connect = true, - ComposeFilter filter_type = AUTO_FILTER) - : connect(connect), filter_type(filter_type) {} -}; - -// Computes the composition of two transducers. This version writes -// the composed FST into a MutableFst. If FST1 transduces string x to -// y with weight a and FST2 transduces y to z with weight b, then -// their composition transduces string x to z with weight -// Times(a, b). -// -// The output labels of the first transducer or the input labels of -// the second transducer must be sorted. The weights need to form a -// commutative semiring (valid for TropicalWeight and LogWeight). -// -// Complexity: -// -// Assuming the first FST is unsorted and the second is sorted: -// -// Time: O(V1 V2 D1 (log D2 + M2)), -// Space: O(V1 V2 D1 M2) -// -// where Vi = # of states, Di = maximum out-degree, and Mi is the maximum -// multiplicity, for the ith FST. -// -// Caveats: -// -// - Compose trims its output. -// - The efficiency of composition can be strongly affected by several factors: -// - the choice of which transducer is sorted - prefer sorting the FST -// that has the greater average out-degree. -// - the amount of non-determinism -// - the presence and location of epsilon transitions - avoid epsilon -// transitions on the output side of the first transducer or -// the input side of the second transducer or prefer placing -// them later in a path since they delay matching and can -// introduce non-coaccessible states and transitions. -template -void Compose(const Fst &ifst1, const Fst &ifst2, - MutableFst *ofst, - const ComposeOptions &opts = ComposeOptions()) { - using M = Matcher>; - // In each case, we cache only the last state for fastest copy. - switch (opts.filter_type) { - case AUTO_FILTER: { - CacheOptions nopts; - nopts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, nopts); - break; - } - case NULL_FILTER: { - ComposeFstOptions> copts; - copts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, copts); - break; - } - case SEQUENCE_FILTER: { - ComposeFstOptions> copts; - copts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, copts); - break; - } - case ALT_SEQUENCE_FILTER: { - ComposeFstOptions> copts; - copts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, copts); - break; - } - case MATCH_FILTER: { - ComposeFstOptions> copts; - copts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, copts); - break; - } - case NO_MATCH_FILTER: { - ComposeFstOptions> copts; - copts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, copts); - break; - } - case TRIVIAL_FILTER: { - ComposeFstOptions> copts; - copts.gc_limit = 0; - *ofst = ComposeFst(ifst1, ifst2, copts); - break; - } - } - if (opts.connect) Connect(ofst); -} - -} // namespace fst - -#endif // FST_COMPOSE_H_ diff --git a/contrib/fstlib/fst/concat.h b/contrib/fstlib/fst/concat.h deleted file mode 100644 index 733cec1..0000000 --- a/contrib/fstlib/fst/concat.h +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to compute the concatenation of two FSTs. - -#ifndef FST_CONCAT_H_ -#define FST_CONCAT_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Computes the concatenation (product) of two FSTs. If FST1 transduces string -// x to y with weight a and FST2 transduces string w to v with weight b, then -// their concatenation transduces string xw to yv with weight Times(a, b). -// -// This version modifies its MutableFst argument (in first position). -// -// Complexity: -// -// Time: O(V1 + V2 + E2) -// Space: O(V1 + V2 + E2) -// -// where Vi is the number of states, and Ei is the number of arcs, of the ith -// FST. -template -void Concat(MutableFst *fst1, const Fst &fst2) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - // Checks that the symbol table are compatible. - if (!CompatSymbols(fst1->InputSymbols(), fst2.InputSymbols()) || - !CompatSymbols(fst1->OutputSymbols(), fst2.OutputSymbols())) { - FSTERROR() << "Concat: Input/output symbol tables of 1st argument " - << "does not match input/output symbol tables of 2nd argument"; - fst1->SetProperties(kError, kError); - return; - } - const auto props1 = fst1->Properties(kFstProperties, false); - const auto props2 = fst2.Properties(kFstProperties, false); - const auto start1 = fst1->Start(); - if (start1 == kNoStateId) { - if (props2 & kError) fst1->SetProperties(kError, kError); - return; - } - const auto numstates1 = fst1->NumStates(); - if (std::optional numstates2 = fst2.NumStatesIfKnown()) { - fst1->ReserveStates(numstates1 + *numstates2); - } - for (StateIterator> siter2(fst2); !siter2.Done(); siter2.Next()) { - const auto s1 = fst1->AddState(); - const auto s2 = siter2.Value(); - fst1->SetFinal(s1, fst2.Final(s2)); - fst1->ReserveArcs(s1, fst2.NumArcs(s2)); - for (ArcIterator> aiter(fst2, s2); !aiter.Done(); aiter.Next()) { - auto arc = aiter.Value(); - arc.nextstate += numstates1; - fst1->AddArc(s1, arc); - } - } - const auto start2 = fst2.Start(); - for (StateId s1 = 0; s1 < numstates1; ++s1) { - const auto weight = fst1->Final(s1); - if (weight != Weight::Zero()) { - fst1->SetFinal(s1, Weight::Zero()); - if (start2 != kNoStateId) { - fst1->AddArc(s1, Arc(0, 0, weight, start2 + numstates1)); - } - } - } - if (start2 != kNoStateId) { - fst1->SetProperties(ConcatProperties(props1, props2), kFstProperties); - } -} - -// Computes the concatentation of two FSTs. This version modifies its -// RationalFst input (in first position). -template -void Concat(RationalFst *fst1, const Fst &fst2) { - fst1->GetMutableImpl()->AddConcat(fst2, true); -} - -// Computes the concatentation of two FSTs. This version modifies its -// MutableFst argument (in second position). -// -// Complexity: -// -// Time: O(V1 + E1) -// Space: O(V1 + E1) -// -// where Vi is the number of states, and Ei is the number of arcs, of the ith -// FST. -template -void Concat(const Fst &fst1, MutableFst *fst2) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - // Checks that the symbol table are compatible. - if (!CompatSymbols(fst1.InputSymbols(), fst2->InputSymbols()) || - !CompatSymbols(fst1.OutputSymbols(), fst2->OutputSymbols())) { - FSTERROR() << "Concat: Input/output symbol tables of 1st argument " - << "does not match input/output symbol tables of 2nd argument"; - fst2->SetProperties(kError, kError); - return; - } - const auto props1 = fst1.Properties(kFstProperties, false); - const auto props2 = fst2->Properties(kFstProperties, false); - const auto start2 = fst2->Start(); - if (start2 == kNoStateId) { - if (props1 & kError) fst2->SetProperties(kError, kError); - return; - } - const auto numstates2 = fst2->NumStates(); - if (std::optional numstates1 = fst1.NumStatesIfKnown()) { - fst2->ReserveStates(numstates2 + *numstates1); - } - for (StateIterator> siter(fst1); !siter.Done(); siter.Next()) { - const auto s1 = siter.Value(); - const auto s2 = fst2->AddState(); - const auto weight = fst1.Final(s1); - if (weight != Weight::Zero()) { - fst2->ReserveArcs(s2, fst1.NumArcs(s1) + 1); - fst2->AddArc(s2, Arc(0, 0, weight, start2)); - } else { - fst2->ReserveArcs(s2, fst1.NumArcs(s1)); - } - for (ArcIterator> aiter(fst1, s1); !aiter.Done(); aiter.Next()) { - auto arc = aiter.Value(); - arc.nextstate += numstates2; - fst2->AddArc(s2, arc); - } - } - const auto start1 = fst1.Start(); - if (start1 != kNoStateId) { - fst2->SetStart(start1 + numstates2); - fst2->SetProperties(ConcatProperties(props1, props2), kFstProperties); - } else { - fst2->SetStart(fst2->AddState()); - } -} - -// Same as the above but can handle arbitrarily many left-hand-side FSTs, -// preallocating the states. -template -void Concat(const std::vector *> &fsts1, MutableFst *fst2) { - fst2->ReserveStates(CountStates(fsts1) + fst2->NumStates()); - for (const auto *fst1 : fsts1) Concat(*fst1, fst2); -} - -// Computes the concatentation of two FSTs. This version modifies its -// RationalFst input (in second position). -template -void Concat(const Fst &fst1, RationalFst *fst2) { - fst2->GetMutableImpl()->AddConcat(fst1, false); -} - -using ConcatFstOptions = RationalFstOptions; - -// Computes the concatenation (product) of two FSTs; this version is a delayed -// FST. If FST1 transduces string x to y with weight a and FST2 transduces -// string w to v with weight b, then their concatenation transduces string xw -// to yv with Times(a, b). -// -// Complexity: -// -// Time: O(v1 + e1 + v2 + e2), -// Space: O(v1 + v2) -// -// where vi is the number of states visited, and ei is the number of arcs -// visited, of the ith FST. Constant time and space to visit an input state or -// arc is assumed and exclusive of caching. -template -class ConcatFst : public RationalFst { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - ConcatFst(const Fst &fst1, const Fst &fst2) { - GetMutableImpl()->InitConcat(fst1, fst2); - } - - ConcatFst(const Fst &fst1, const Fst &fst2, - const ConcatFstOptions &opts) - : RationalFst(opts) { - GetMutableImpl()->InitConcat(fst1, fst2); - } - - // See Fst<>::Copy() for doc. - ConcatFst(const ConcatFst &fst, bool safe = false) - : RationalFst(fst, safe) {} - - // Get a copy of this ConcatFst. See Fst<>::Copy() for further doc. - ConcatFst *Copy(bool safe = false) const override { - return new ConcatFst(*this, safe); - } - - private: - using ImplToFst>::GetImpl; - using ImplToFst>::GetMutableImpl; -}; - -// Specialization for ConcatFst. -template -class StateIterator> : public StateIterator> { - public: - explicit StateIterator(const ConcatFst &fst) - : StateIterator>(fst) {} -}; - -// Specialization for ConcatFst. -template -class ArcIterator> : public ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const ConcatFst &fst, StateId s) - : ArcIterator>(fst, s) {} -}; - -// Useful alias when using StdArc. -using StdConcatFst = ConcatFst; - -} // namespace fst - -#endif // FST_CONCAT_H_ diff --git a/contrib/fstlib/fst/connect.h b/contrib/fstlib/fst/connect.h deleted file mode 100644 index 005b276..0000000 --- a/contrib/fstlib/fst/connect.h +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes and functions to remove unsuccessful paths from an FST. - -#ifndef FST_CONNECT_H_ -#define FST_CONNECT_H_ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -// Trims an FST, removing states and arcs that are not on successful paths. -// This version modifies its input. -// -// Complexity: -// -// Time: O(V + E) -// Space: O(V + E) -// -// where V = # of states and E = # of arcs. -template -void Connect(MutableFst *fst) { - using StateId = typename Arc::StateId; - std::vector access; - std::vector coaccess; - uint64_t props = 0; - SccVisitor scc_visitor(nullptr, &access, &coaccess, &props); - DfsVisit(*fst, &scc_visitor); - std::vector dstates; - dstates.reserve(access.size()); - for (StateId s = 0; s < access.size(); ++s) { - if (!access[s] || !coaccess[s]) dstates.push_back(s); - } - fst->DeleteStates(dstates); - fst->SetProperties(kAccessible | kCoAccessible, kAccessible | kCoAccessible); -} - -// Returns an acyclic FST where each SCC in the input FST has been condensed to -// a single state with transitions between SCCs retained and within SCCs -// dropped. Also populates 'scc' with a mapping from input to output states. -template -void Condense(const Fst &ifst, MutableFst *ofst, - std::vector *scc) { - using StateId = typename Arc::StateId; - ofst->DeleteStates(); - uint64_t props = 0; - SccVisitor scc_visitor(scc, nullptr, nullptr, &props); - DfsVisit(ifst, &scc_visitor); - const auto iter = std::max_element(scc->cbegin(), scc->cend()); - if (iter == scc->cend()) return; - const StateId num_condensed_states = 1 + *iter; - ofst->ReserveStates(num_condensed_states); - for (StateId c = 0; c < num_condensed_states; ++c) { - ofst->AddState(); - } - for (StateId s = 0; s < scc->size(); ++s) { - const auto c = (*scc)[s]; - if (s == ifst.Start()) ofst->SetStart(c); - const auto weight = ifst.Final(s); - if (weight != Arc::Weight::Zero()) - ofst->SetFinal(c, Plus(ofst->Final(c), weight)); - for (ArcIterator> aiter(ifst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - const auto nextc = (*scc)[arc.nextstate]; - if (nextc != c) { - Arc condensed_arc = arc; - condensed_arc.nextstate = nextc; - ofst->AddArc(c, std::move(condensed_arc)); - } - } - } - ofst->SetProperties(kAcyclic | kInitialAcyclic, kAcyclic | kInitialAcyclic); -} - -} // namespace fst - -#endif // FST_CONNECT_H_ diff --git a/contrib/fstlib/fst/const-fst.h b/contrib/fstlib/fst/const-fst.h deleted file mode 100644 index 6eed948..0000000 --- a/contrib/fstlib/fst/const-fst.h +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Simple concrete immutable FST whose states and arcs are each stored in -// single arrays. - -#ifndef FST_CONST_FST_H_ -#define FST_CONST_FST_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -template -class ConstFst; - -template -void Cast(const F &, G *); - -namespace internal { - -// States and arcs each implemented by single arrays, templated on the -// Arc definition. Unsigned is used to represent indices into the arc array. -template -class ConstFstImpl : public FstImpl { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::Properties; - - ConstFstImpl() { - std::string type = "const"; - if (sizeof(Unsigned) != sizeof(uint32_t)) { - type += std::to_string(CHAR_BIT * sizeof(Unsigned)); - } - SetType(type); - SetProperties(kNullProperties | kStaticProperties); - } - - explicit ConstFstImpl(const Fst &fst); - - StateId Start() const { return start_; } - - Weight Final(StateId s) const { return states_[s].final_weight; } - - StateId NumStates() const { return nstates_; } - - size_t NumArcs(StateId s) const { return states_[s].narcs; } - - size_t NumInputEpsilons(StateId s) const { return states_[s].niepsilons; } - - size_t NumOutputEpsilons(StateId s) const { return states_[s].noepsilons; } - - static ConstFstImpl *Read(std::istream &strm, const FstReadOptions &opts); - - const Arc *Arcs(StateId s) const { return arcs_ + states_[s].pos; } - - // Provide information needed for generic state iterator. - void InitStateIterator(StateIteratorData *data) const { - data->base = nullptr; - data->nstates = nstates_; - } - - // Provide information needed for the generic arc iterator. - void InitArcIterator(StateId s, ArcIteratorData *data) const { - data->base = nullptr; - data->arcs = arcs_ + states_[s].pos; - data->narcs = states_[s].narcs; - data->ref_count = nullptr; - } - - private: - // Used to find narcs_ and nstates_ in Write. - friend class ConstFst; - - // States implemented by array *states_ below, arcs by (single) *arcs_. - struct ConstState { - Weight final_weight; // Final weight. - Unsigned pos; // Start of state's arcs in *arcs_. - Unsigned narcs; // Number of arcs (per state). - Unsigned niepsilons; // Number of input epsilons. - Unsigned noepsilons; // Number of output epsilons. - - ConstState() : final_weight(Weight::Zero()) {} - }; - - // Properties always true of this FST class. - static constexpr uint64_t kStaticProperties = kExpanded; - // Current unaligned file format version. The unaligned version was added and - // made the default since the aligned version does not work on pipes. - static constexpr int kFileVersion = 2; - // Current aligned file format version. - static constexpr int kAlignedFileVersion = 1; - // Minimum file format version supported. - static constexpr int kMinFileVersion = 1; - - std::unique_ptr states_region_; // Mapped file for states. - std::unique_ptr arcs_region_; // Mapped file for arcs. - ConstState *states_ = nullptr; // States representation. - Arc *arcs_ = nullptr; // Arcs representation. - size_t narcs_ = 0; // Number of arcs. - StateId nstates_ = 0; // Number of states. - StateId start_ = kNoStateId; // Initial state. - - ConstFstImpl(const ConstFstImpl &) = delete; - ConstFstImpl &operator=(const ConstFstImpl &) = delete; -}; - -template -ConstFstImpl::ConstFstImpl(const Fst &fst) { - std::string type = "const"; - if (sizeof(Unsigned) != sizeof(uint32_t)) { - type += std::to_string(CHAR_BIT * sizeof(Unsigned)); - } - SetType(type); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - start_ = fst.Start(); - // Counts states and arcs. - for (StateIterator> siter(fst); !siter.Done(); siter.Next()) { - ++nstates_; - narcs_ += fst.NumArcs(siter.Value()); - } - states_region_.reset(MappedFile::AllocateType(nstates_)); - arcs_region_.reset(MappedFile::AllocateType(narcs_)); - states_ = static_cast(states_region_->mutable_data()); - arcs_ = static_cast(arcs_region_->mutable_data()); - size_t pos = 0; - for (StateId s = 0; s < nstates_; ++s) { - states_[s].final_weight = fst.Final(s); - states_[s].pos = pos; - states_[s].narcs = 0; - states_[s].niepsilons = 0; - states_[s].noepsilons = 0; - for (ArcIterator> aiter(fst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - ++states_[s].narcs; - if (arc.ilabel == 0) ++states_[s].niepsilons; - if (arc.olabel == 0) ++states_[s].noepsilons; - arcs_[pos] = arc; - ++pos; - } - } - const auto props = - fst.Properties(kMutable, false) - ? fst.Properties(kCopyProperties, true) - : CheckProperties( - fst, kCopyProperties & ~kWeightedCycles & ~kUnweightedCycles, - kCopyProperties); - SetProperties(props | kStaticProperties); -} - -template -ConstFstImpl *ConstFstImpl::Read( - std::istream &strm, const FstReadOptions &opts) { - auto impl = std::make_unique(); - FstHeader hdr; - if (!impl->ReadHeader(strm, opts, kMinFileVersion, &hdr)) return nullptr; - impl->start_ = hdr.Start(); - impl->nstates_ = hdr.NumStates(); - impl->narcs_ = hdr.NumArcs(); - // Ensures compatibility. - if (hdr.Version() == kAlignedFileVersion) { - hdr.SetFlags(hdr.GetFlags() | FstHeader::IS_ALIGNED); - } - if ((hdr.GetFlags() & FstHeader::IS_ALIGNED) && !AlignInput(strm)) { - LOG(ERROR) << "ConstFst::Read: Alignment failed: " << opts.source; - return nullptr; - } - size_t b = impl->nstates_ * sizeof(ConstState); - impl->states_region_.reset( - MappedFile::Map(strm, opts.mode == FstReadOptions::MAP, opts.source, b)); - if (!strm || !impl->states_region_) { - LOG(ERROR) << "ConstFst::Read: Read failed: " << opts.source; - return nullptr; - } - impl->states_ = - static_cast(impl->states_region_->mutable_data()); - if ((hdr.GetFlags() & FstHeader::IS_ALIGNED) && !AlignInput(strm)) { - LOG(ERROR) << "ConstFst::Read: Alignment failed: " << opts.source; - return nullptr; - } - b = impl->narcs_ * sizeof(Arc); - impl->arcs_region_.reset( - MappedFile::Map(strm, opts.mode == FstReadOptions::MAP, opts.source, b)); - if (!strm || !impl->arcs_region_) { - LOG(ERROR) << "ConstFst::Read: Read failed: " << opts.source; - return nullptr; - } - impl->arcs_ = static_cast(impl->arcs_region_->mutable_data()); - return impl.release(); -} - -} // namespace internal - -// Simple concrete immutable FST. This class attaches interface to -// implementation and handles reference counting, delegating most methods to -// ImplToExpandedFst. The unsigned type U is used to represent indices into the -// arc array (default declared in fst-decl.h). -// -// ConstFst is thread-safe. -template -class ConstFst : public ImplToExpandedFst> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using Impl = internal::ConstFstImpl; - using ConstState = typename Impl::ConstState; - - friend class StateIterator>; - friend class ArcIterator>; - - template - void friend Cast(const F &, G *); - - ConstFst() : ImplToExpandedFst(std::make_shared()) {} - - explicit ConstFst(const Fst &fst) - : ImplToExpandedFst(std::make_shared(fst)) {} - - ConstFst(const ConstFst &fst, bool unused_safe = false) - : ImplToExpandedFst(fst.GetSharedImpl()) {} - - // Gets a copy of this ConstFst. See Fst<>::Copy() for further doc. - ConstFst *Copy(bool safe = false) const override { - return new ConstFst(*this, safe); - } - - // Reads a ConstFst from an input stream, returning nullptr on error. - static ConstFst *Read(std::istream &strm, const FstReadOptions &opts) { - auto *impl = Impl::Read(strm, opts); - return impl ? new ConstFst(std::shared_ptr(impl)) : nullptr; - } - - // Read a ConstFst from a file; return nullptr on error; empty source reads - // from standard input. - static ConstFst *Read(std::string_view source) { - auto *impl = ImplToExpandedFst::Read(source); - return impl ? new ConstFst(std::shared_ptr(impl)) : nullptr; - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const override { - return WriteFst(*this, strm, opts); - } - - bool Write(const std::string &source) const override { - return Fst::WriteFile(source); - } - - template - static bool WriteFst(const FST &fst, std::ostream &strm, - const FstWriteOptions &opts); - - void InitStateIterator(StateIteratorData *data) const override { - GetImpl()->InitStateIterator(data); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetImpl()->InitArcIterator(s, data); - } - - private: - explicit ConstFst(std::shared_ptr impl) - : ImplToExpandedFst(impl) {} - - using ImplToFst>::GetImpl; - - // Uses overloading to extract the type of the argument. - static const Impl *GetImplIfConstFst(const ConstFst &const_fst) { - return const_fst.GetImpl(); - } - - // NB: this does not give privileged treatment to subtypes of ConstFst. - template - static Impl *GetImplIfConstFst(const FST &fst) { - return nullptr; - } - - ConstFst &operator=(const ConstFst &) = delete; -}; - -// Writes FST in Const format, potentially with a pass over the machine before -// writing to compute number of states and arcs. -template -template -bool ConstFst::WriteFst(const FST &fst, std::ostream &strm, - const FstWriteOptions &opts) { - const auto file_version = - opts.align ? internal::ConstFstImpl::kAlignedFileVersion - : internal::ConstFstImpl::kFileVersion; - size_t num_arcs = 0; // To silence -Wsometimes-uninitialized warnings. - size_t num_states = 0; // Ditto. - std::streamoff start_offset = 0; - bool update_header = true; - if (const auto *impl = GetImplIfConstFst(fst)) { - num_arcs = impl->narcs_; - num_states = impl->nstates_; - update_header = false; - } else if (opts.stream_write || (start_offset = strm.tellp()) == -1) { - // precompute values needed for header when we cannot seek to rewrite it. - num_arcs = 0; - num_states = 0; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - num_arcs += fst.NumArcs(siter.Value()); - ++num_states; - } - update_header = false; - } - FstHeader hdr; - hdr.SetStart(fst.Start()); - hdr.SetNumStates(num_states); - hdr.SetNumArcs(num_arcs); - std::string type = "const"; - if (sizeof(Unsigned) != sizeof(uint32_t)) { - type += std::to_string(CHAR_BIT * sizeof(Unsigned)); - } - const auto properties = - fst.Properties(kCopyProperties, true) | - internal::ConstFstImpl::kStaticProperties; - internal::FstImpl::WriteFstHeader(fst, strm, opts, file_version, type, - properties, &hdr); - if (opts.align && !AlignOutput(strm)) { - LOG(ERROR) << "Could not align file during write after header"; - return false; - } - size_t pos = 0; - size_t states = 0; - ConstState state; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - state.final_weight = fst.Final(s); - state.pos = pos; - state.narcs = fst.NumArcs(s); - state.niepsilons = fst.NumInputEpsilons(s); - state.noepsilons = fst.NumOutputEpsilons(s); - strm.write(reinterpret_cast(&state), sizeof(state)); - pos += state.narcs; - ++states; - } - hdr.SetNumStates(states); - hdr.SetNumArcs(pos); - if (opts.align && !AlignOutput(strm)) { - LOG(ERROR) << "Could not align file during write after writing states"; - } - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - for (ArcIterator aiter(fst, siter.Value()); !aiter.Done(); - aiter.Next()) { - const auto &arc = aiter.Value(); - strm.write(reinterpret_cast(&arc), sizeof(arc)); - } - } - strm.flush(); - if (!strm) { - LOG(ERROR) << "ConstFst::WriteFst: Write failed: " << opts.source; - return false; - } - if (update_header) { - return internal::FstImpl::UpdateFstHeader( - fst, strm, opts, file_version, type, properties, &hdr, start_offset); - } else { - if (hdr.NumStates() != num_states) { - LOG(ERROR) << "Inconsistent number of states observed during write"; - return false; - } - if (hdr.NumArcs() != num_arcs) { - LOG(ERROR) << "Inconsistent number of arcs observed during write"; - return false; - } - } - return true; -} - -// Specialization for ConstFst; see generic version in fst.h for sample usage -// (but use the ConstFst type instead). This version should inline. -template -class StateIterator> { - public: - using StateId = typename Arc::StateId; - - explicit StateIterator(const ConstFst &fst) - : nstates_(fst.GetImpl()->NumStates()), s_(0) {} - - bool Done() const { return s_ >= nstates_; } - - StateId Value() const { return s_; } - - void Next() { ++s_; } - - void Reset() { s_ = 0; } - - private: - const StateId nstates_; - StateId s_; -}; - -// Specialization for ConstFst; see generic version in fst.h for sample usage -// (but use the ConstFst type instead). This version should inline. -template -class ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const ConstFst &fst, StateId s) - : arcs_(fst.GetImpl()->Arcs(s)), - narcs_(fst.GetImpl()->NumArcs(s)), - i_(0) {} - - bool Done() const { return i_ >= narcs_; } - - const Arc &Value() const { return arcs_[i_]; } - - void Next() { ++i_; } - - size_t Position() const { return i_; } - - void Reset() { i_ = 0; } - - void Seek(size_t a) { i_ = a; } - - constexpr uint8_t Flags() const { return kArcValueFlags; } - - void SetFlags(uint8_t, uint8_t) {} - - private: - const Arc *arcs_; - size_t narcs_; - size_t i_; -}; - -// A useful alias when using StdArc. -using StdConstFst = ConstFst; - -} // namespace fst - -#endif // FST_CONST_FST_H_ diff --git a/contrib/fstlib/fst/determinize.h b/contrib/fstlib/fst/determinize.h deleted file mode 100644 index 3b4f8c7..0000000 --- a/contrib/fstlib/fst/determinize.h +++ /dev/null @@ -1,1133 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to determinize an FST. - -#ifndef FST_DETERMINIZE_H_ -#define FST_DETERMINIZE_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Common divisors are used in determinization to compute transition weights. -// In the simplest case, it is the same as semiring Plus, but other choices -// permit more efficient determinization when the output contains strings. - -// The default common divisor uses the semiring Plus. -namespace internal { -template -class RelationDeterminizeFilter; -} // namespace internal -struct PairArc; - -template -struct DefaultCommonDivisor { - public: - using Weight = W; - - Weight operator()(const Weight &w1, const Weight &w2) const { - return Plus(w1, w2); - } -}; - -// The label common divisor for a (left) string semiring selects a single -// letter common prefix or the empty string. This is used in the -// determinization of output strings so that at most a single letter will -// appear in the output of a transtion. -template -struct LabelCommonDivisor { - public: - using Weight = StringWeight; - - Weight operator()(const Weight &w1, const Weight &w2) const { - typename Weight::Iterator iter1(w1); - typename Weight::Iterator iter2(w2); - if (!(StringWeight::Properties() & kLeftSemiring)) { - FSTERROR() << "LabelCommonDivisor: Weight needs to be left semiring"; - return Weight::NoWeight(); - } else if (w1.Size() == 0 || w2.Size() == 0) { - return Weight::One(); - } else if (w1 == Weight::Zero()) { - return Weight(iter2.Value()); - } else if (w2 == Weight::Zero()) { - return Weight(iter1.Value()); - } else if (iter1.Value() == iter2.Value()) { - return Weight(iter1.Value()); - } else { - return Weight::One(); - } - } -}; - -// The gallic common divisor uses the label common divisor on the string -// component and the common divisor on the weight component, which defaults to -// the default common divisor. -template > -class GallicCommonDivisor { - public: - using Weight = GallicWeight; - - Weight operator()(const Weight &w1, const Weight &w2) const { - return Weight(label_common_divisor_(w1.Value1(), w2.Value1()), - weight_common_divisor_(w1.Value2(), w2.Value2())); - } - - private: - LabelCommonDivisor label_common_divisor_; - CommonDivisor weight_common_divisor_; -}; - -// Specialization for general GALLIC weight. -template -class GallicCommonDivisor { - public: - using Weight = GallicWeight; - using GRWeight = GallicWeight; - using Iterator = - UnionWeightIterator>; - - Weight operator()(const Weight &w1, const Weight &w2) const { - auto weight = GRWeight::Zero(); - for (Iterator iter(w1); !iter.Done(); iter.Next()) { - weight = common_divisor_(weight, iter.Value()); - } - for (Iterator iter(w2); !iter.Done(); iter.Next()) { - weight = common_divisor_(weight, iter.Value()); - } - return weight == GRWeight::Zero() ? Weight::Zero() : Weight(weight); - } - - private: - GallicCommonDivisor common_divisor_; -}; - -namespace internal { - -// Represents an element in a subset -template -struct DeterminizeElement { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - DeterminizeElement(StateId s, Weight weight) - : state_id(s), weight(std::move(weight)) {} - - inline bool operator==(const DeterminizeElement &element) const { - return state_id == element.state_id && weight == element.weight; - } - - inline bool operator!=(const DeterminizeElement &element) const { - return !(*this == element); - } - - inline bool operator<(const DeterminizeElement &element) const { - return state_id < element.state_id; - } - - StateId state_id; // Input state ID. - Weight weight; // Residual weight. -}; - -// Represents a weighted subset and determinization filter state -template -struct DeterminizeStateTuple { - using Arc = A; - using Element = DeterminizeElement; - using Subset = std::forward_list; - - DeterminizeStateTuple() : filter_state(FilterState::NoState()) {} - - inline bool operator==(const DeterminizeStateTuple &tuple) const { - return (tuple.filter_state == filter_state) && (tuple.subset == subset); - } - - inline bool operator!=(const DeterminizeStateTuple &tuple) const { - return (tuple.filter_state != filter_state) || (tuple.subset != subset); - } - - Subset subset; - FilterState filter_state; -}; - -// Proto-transition for determinization. -template -struct DeterminizeArc { - using Arc = typename StateTuple::Arc; - using Label = typename Arc::Label; - using Weight = typename Arc::Weight; - - DeterminizeArc() = default; - - explicit DeterminizeArc(const Arc &arc) - : label(arc.ilabel), - dest_tuple(fst::make_unique_for_overwrite()) {} - - Label label = kNoLabel; // Arc label. - Weight weight = Weight::Zero(); // Arc weight. - std::unique_ptr - dest_tuple; // Destination subset and filter state. -}; - -} // namespace internal - -// Determinization filters are used to compute destination state tuples based -// on the source tuple, transition, and destination element or on similar -// super-final transition information. The filter operates on a map between a -// label and the corresponding destination state tuples. It must define the map -// type LabelMap. The default filter is used for weighted determinization. -// A determinize filter for implementing weighted determinization. -template -class DefaultDeterminizeFilter { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FilterState = CharFilterState; - using Element = internal::DeterminizeElement; - using StateTuple = internal::DeterminizeStateTuple; - using LabelMap = std::map>; - - // This is needed e.g. to go into the gallic domain for transducers. - template - struct rebind { - using Other = DefaultDeterminizeFilter; - }; - - explicit DefaultDeterminizeFilter(const Fst &fst) : fst_(fst.Copy()) {} - - // This is needed (e.g.) to go into the gallic domain for transducers. - template - DefaultDeterminizeFilter(const Fst &fst, std::unique_ptr filter) - : fst_(fst.Copy()) {} - - // Copy constructor; the FST can be passed if it has been deep-copied. - DefaultDeterminizeFilter(const DefaultDeterminizeFilter &filter, - const Fst *fst = nullptr) - : fst_(fst ? fst->Copy() : filter.fst_->Copy()) {} - - FilterState Start() const { return FilterState(0); } - - // Does no work. - void SetState(StateId s, const StateTuple &tuple) {} - - // Filters transition, possibly modifying label map. Returns true if arc is - // added to the label map. - bool FilterArc(const Arc &arc, const Element &src_element, - Element &&dest_element, LabelMap *label_map) const { - // Adds element to unique state tuple for arc label. - auto &det_arc = (*label_map)[arc.ilabel]; - if (det_arc.label == kNoLabel) { - det_arc = internal::DeterminizeArc(arc); - det_arc.dest_tuple->filter_state = FilterState(0); - } - det_arc.dest_tuple->subset.push_front(std::move(dest_element)); - return true; - } - - // Filters super-final transition, returning new final weight. - Weight FilterFinal(Weight weight, const Element &element) { return weight; } - - static uint64_t Properties(uint64_t props) { return props; } - - private: - std::unique_ptr> fst_; -}; - -// Determinization state table interface: -// -// template -// class DeterminizeStateTable { -// public: -// using StateId = typename Arc::StateId; -// using StateTuple = internal::DeterminizeStateTuple; -// -// // Required sub-class. This is needed (e.g.) to go into the gallic domain. -// template -// struct rebind { -// using Other = DeterminizeStateTable; -// } -// -// // Required constuctor. -// DeterminizeStateTable(); -// -// // Required copy constructor that does not copy state. -// DeterminizeStateTable(const DeterminizeStateTable -// &table); -// -// // Looks up state ID by state tuple; if it doesn't exist, then adds it. -// // FindState takes ownership of the state tuple argument so that it -// // doesn't have to copy it if it creates a new state. -// StateId FindState(std::unique_ptr tuple); -// -// // Looks up state tuple by ID. -// const StateTuple *Tuple(StateId id) const; -// }; - -// The default determinization state table based on the compact hash bi-table. -template -class DefaultDeterminizeStateTable { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using StateTuple = internal::DeterminizeStateTuple; - using Element = typename StateTuple::Element; - using Subset = typename StateTuple::Subset; - - template - struct rebind { - using Other = DefaultDeterminizeStateTable; - }; - - explicit DefaultDeterminizeStateTable(size_t table_size = 0) - : table_size_(table_size), tuples_(table_size_) {} - - DefaultDeterminizeStateTable(const DefaultDeterminizeStateTable &table) - : table_size_(table.table_size_), tuples_(table_size_) {} - - ~DefaultDeterminizeStateTable() { - for (StateId s = 0; s < tuples_.Size(); ++s) delete tuples_.FindEntry(s); - } - - // Finds the state corresponding to a state tuple. Only creates a new state if - // the tuple is not found. FindState takes ownership of the tuple argument so - // that it doesn't have to copy it if it creates a new state. - StateId FindState(std::unique_ptr tuple) { - StateTuple *raw_tuple = tuple.release(); - const StateId ns = tuples_.Size(); - // TODO(wolfsonkin): Make CompactHashBiTable support move semantics so we - // can store a `std::unique_ptr` in `tuples_`. - const auto s = tuples_.FindId(raw_tuple); - if (s != ns) delete raw_tuple; // Tuple found. - return s; - } - - const StateTuple *Tuple(StateId s) { return tuples_.FindEntry(s); } - - private: - // Comparison object for StateTuples. - class StateTupleEqual { - public: - bool operator()(const StateTuple *tuple1, const StateTuple *tuple2) const { - return *tuple1 == *tuple2; - } - }; - - // Hash function for StateTuples. - class StateTupleKey { - public: - size_t operator()(const StateTuple *tuple) const { - size_t h = tuple->filter_state.Hash(); - for (auto &element : tuple->subset) { - const size_t h1 = element.state_id; - static constexpr auto lshift = 5; - static constexpr auto rshift = CHAR_BIT * sizeof(size_t) - 5; - h ^= h << 1 ^ h1 << lshift ^ h1 >> rshift ^ element.weight.Hash(); - } - return h; - } - }; - - size_t table_size_; - CompactHashBiTable - tuples_; - - DefaultDeterminizeStateTable &operator=( - const DefaultDeterminizeStateTable &) = delete; -}; - -// Determinization type. -enum DeterminizeType { - // Input transducer is known to be functional (or error). - DETERMINIZE_FUNCTIONAL, // Input transducer is functional (error if not). - // Input transducer is not known to be functional. - DETERMINIZE_NONFUNCTIONAL, - // Input transducer is not known to be functional but only keep the min of - // of ambiguous outputs. - DETERMINIZE_DISAMBIGUATE -}; - -// Options for finite-state transducer determinization templated on the arc -// type, common divisor, the determinization filter and the state table. -// DeterminizeFst takes ownership of the determinization filter and state table, -// if provided. -template , - class Filter = DefaultDeterminizeFilter, - class StateTable = - DefaultDeterminizeStateTable> -struct DeterminizeFstOptions : public CacheOptions { - using Label = typename Arc::Label; - - float delta; // Quantization delta for subset weights. - Label subsequential_label; // Label used for residual final output - // when producing subsequential transducers. - DeterminizeType type; // Determinization type. - bool increment_subsequential_label; // When creating several subsequential - // arcs at a given state, make their - // label distinct by incrementing. - Filter *filter; // Determinization filter; - // DeterminizeFst takes ownership. - StateTable *state_table; // Determinization state table; - // DeterminizeFst takes ownership. - - explicit DeterminizeFstOptions(const CacheOptions &opts, float delta = kDelta, - Label subsequential_label = 0, - DeterminizeType type = DETERMINIZE_FUNCTIONAL, - bool increment_subsequential_label = false, - Filter *filter = nullptr, - StateTable *state_table = nullptr) - : CacheOptions(opts), - delta(delta), - subsequential_label(subsequential_label), - type(type), - increment_subsequential_label(increment_subsequential_label), - filter(filter), - state_table(state_table) {} - - explicit DeterminizeFstOptions(float delta = kDelta, - Label subsequential_label = 0, - DeterminizeType type = DETERMINIZE_FUNCTIONAL, - bool increment_subsequential_label = false, - Filter *filter = nullptr, - StateTable *state_table = nullptr) - : delta(delta), - subsequential_label(subsequential_label), - type(type), - increment_subsequential_label(increment_subsequential_label), - filter(filter), - state_table(state_table) {} -}; - -namespace internal { - -// Implementation of delayed DeterminizeFst. This base class is -// common to the variants that implement acceptor and transducer -// determinization. -template -class DeterminizeFstImplBase : public CacheImpl { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::Properties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheBaseImpl>::HasStart; - using CacheBaseImpl>::HasFinal; - using CacheBaseImpl>::HasArcs; - using CacheBaseImpl>::SetFinal; - using CacheBaseImpl>::SetStart; - - template - DeterminizeFstImplBase( - const Fst &fst, - const DeterminizeFstOptions &opts) - : CacheImpl(opts), fst_(fst.Copy()) { - SetType("determinize"); - const auto iprops = fst.Properties(kFstProperties, false); - const auto dprops = - DeterminizeProperties(iprops, opts.subsequential_label != 0, - opts.type == DETERMINIZE_NONFUNCTIONAL - ? opts.increment_subsequential_label - : true); - SetProperties(Filter::Properties(dprops), kCopyProperties); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - } - - DeterminizeFstImplBase(const DeterminizeFstImplBase &impl) - : CacheImpl(impl), fst_(impl.fst_->Copy(true)) { - SetType("determinize"); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - virtual DeterminizeFstImplBase *Copy() const = 0; - - StateId Start() { - if (!HasStart()) { - const auto start = ComputeStart(); - if (start != kNoStateId) SetStart(start); - } - return CacheImpl::Start(); - } - - Weight Final(StateId s) { - if (!HasFinal(s)) SetFinal(s, ComputeFinal(s)); - return CacheImpl::Final(s); - } - - virtual void Expand(StateId s) = 0; - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - virtual StateId ComputeStart() = 0; - - virtual Weight ComputeFinal(StateId s) = 0; - - const Fst &GetFst() const { return *fst_; } - - private: - std::unique_ptr> fst_; // Input FST. -}; - -// Implementation of delayed determinization for weighted acceptors. -template -class DeterminizeFsaImpl : public DeterminizeFstImplBase { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FilterState = typename Filter::FilterState; - using StateTuple = internal::DeterminizeStateTuple; - using Element = typename StateTuple::Element; - using Subset = typename StateTuple::Subset; - using LabelMap = typename Filter::LabelMap; - - using FstImpl::SetProperties; - using DeterminizeFstImplBase::GetFst; - using DeterminizeFstImplBase::SetArcs; - - DeterminizeFsaImpl( - const Fst &fst, const std::vector *in_dist, - std::vector *out_dist, - const DeterminizeFstOptions &opts) - : DeterminizeFstImplBase(fst, opts), - delta_(opts.delta), - in_dist_(in_dist), - out_dist_(out_dist), - filter_(opts.filter ? opts.filter : new Filter(fst)), - state_table_(opts.state_table ? opts.state_table : new StateTable()) { - if (!fst.Properties(kAcceptor, true)) { - FSTERROR() << "DeterminizeFst: Argument not an acceptor"; - SetProperties(kError, kError); - } - if (!(Weight::Properties() & kLeftSemiring)) { - FSTERROR() << "DeterminizeFst: Weight must be left distributive: " - << Weight::Type(); - SetProperties(kError, kError); - } - if (out_dist_) out_dist_->clear(); - } - - DeterminizeFsaImpl(const DeterminizeFsaImpl &impl) - : DeterminizeFstImplBase(impl), - delta_(impl.delta_), - in_dist_(nullptr), - out_dist_(nullptr), - filter_(new Filter(*impl.filter_, &GetFst())), - state_table_(new StateTable(*impl.state_table_)) { - if (impl.out_dist_) { - FSTERROR() << "DeterminizeFsaImpl: Cannot copy with out_dist vector"; - SetProperties(kError, kError); - } - } - - DeterminizeFsaImpl *Copy() const override { - return new DeterminizeFsaImpl(*this); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && (GetFst().Properties(kError, false))) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - StateId ComputeStart() override { - const auto s = GetFst().Start(); - if (s == kNoStateId) return kNoStateId; - auto tuple = fst::make_unique_for_overwrite(); - tuple->subset.emplace_front(s, Weight::One()); - tuple->filter_state = filter_->Start(); - return FindState(std::move(tuple)); - } - - Weight ComputeFinal(StateId s) override { - const auto *tuple = state_table_->Tuple(s); - filter_->SetState(s, *tuple); - auto final_weight = Weight::Zero(); - for (const auto &element : tuple->subset) { - final_weight = - Plus(final_weight, - Times(element.weight, GetFst().Final(element.state_id))); - final_weight = filter_->FilterFinal(final_weight, element); - if (!final_weight.Member()) SetProperties(kError, kError); - } - return final_weight; - } - - StateId FindState(std::unique_ptr tuple) { - const auto &subset = tuple->subset; - const auto s = state_table_->FindState(std::move(tuple)); - if (in_dist_ && out_dist_->size() <= s) { - out_dist_->push_back(ComputeDistance(subset)); - } - return s; - } - - // Computes distance from a state to the final states in the DFA given the - // distances in the NFA. - Weight ComputeDistance(const Subset &subset) { - auto outd = Weight::Zero(); - for (const auto &element : subset) { - const auto ind = - (element.state_id < in_dist_->size() ? (*in_dist_)[element.state_id] - : Weight::Zero()); - outd = Plus(outd, Times(element.weight, ind)); - } - return outd; - } - - // Computes the outgoing transitions from a state, creating new destination - // states as needed. - void Expand(StateId s) override { - LabelMap label_map; - GetLabelMap(s, &label_map); - for (auto &[unused_label, arc] : label_map) { - AddArc(s, std::move(arc)); - } - SetArcs(s); - } - - private: - using DetArc = internal::DeterminizeArc; - - // Constructs proto-determinization transition, including destination subset, - // per label. - void GetLabelMap(StateId s, LabelMap *label_map) { - const auto *src_tuple = state_table_->Tuple(s); - filter_->SetState(s, *src_tuple); - for (const auto &src_element : src_tuple->subset) { - for (ArcIterator> aiter(GetFst(), src_element.state_id); - !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - Element dest_element(arc.nextstate, - Times(src_element.weight, arc.weight)); - filter_->FilterArc(arc, src_element, std::move(dest_element), - label_map); - } - } - for (auto &[unused_label, arc] : *label_map) { - NormArc(&arc); - } - } - - // Sorts subsets and removes duplicate elements, normalizing transition and - // subset weights. - void NormArc(DetArc *det_arc) { - auto &dest_subset = det_arc->dest_tuple->subset; - dest_subset.sort(); - auto piter = dest_subset.begin(); - for (auto diter = dest_subset.begin(); diter != dest_subset.end(); ) { - auto &dest_element = *diter; - auto &prev_element = *piter; - // Computes arc weight. - det_arc->weight = common_divisor_(det_arc->weight, dest_element.weight); - if (piter != diter && dest_element.state_id == prev_element.state_id) { - // Found duplicate state: sums state weight and deletes duplicate. - prev_element.weight = Plus(prev_element.weight, dest_element.weight); - if (!prev_element.weight.Member()) SetProperties(kError, kError); - ++diter; - dest_subset.erase_after(piter); - } else { - piter = diter; - ++diter; - } - } - // Divides out label weight from destination subset elements, quantizing to - // ensure comparisons are effective. - for (auto &dest_element : dest_subset) { - dest_element.weight = - Divide(dest_element.weight, det_arc->weight, DIVIDE_LEFT); - dest_element.weight = dest_element.weight.Quantize(delta_); - } - } - - // Adds an arc from state S to the destination state associated with state - // tuple in det_arc as created by GetLabelMap. - void AddArc(StateId s, DetArc &&det_arc) { - CacheImpl::EmplaceArc(s, det_arc.label, det_arc.label, - std::move(det_arc.weight), - FindState(std::move(det_arc.dest_tuple))); - } - - float delta_; // Quantization delta for weights. - const std::vector *in_dist_; // Distance to final NFA states. - std::vector *out_dist_; // Distance to final DFA states. - - static const CommonDivisor common_divisor_; - std::unique_ptr filter_; - std::unique_ptr state_table_; -}; - -template -const CommonDivisor DeterminizeFsaImpl::common_divisor_{}; - -// Implementation of delayed determinization for transducers. Transducer -// determinization is implemented by mapping the input to the Gallic semiring as -// an acceptor whose weights contain the output strings and using acceptor -// determinization above to determinize that acceptor. -template -class DeterminizeFstImpl : public DeterminizeFstImplBase { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using ToMapper = ToGallicMapper; - using ToArc = typename ToMapper::ToArc; - using ToFst = ArcMapFst; - using FromMapper = FromGallicMapper; - using FromFst = ArcMapFst; - - using ToCommonDivisor = GallicCommonDivisor; - using ToFilter = typename Filter::template rebind::Other; - using ToFilterState = typename ToFilter::FilterState; - using ToStateTable = - typename StateTable::template rebind::Other; - using FactorIterator = GallicFactor; - - using FstImpl::SetProperties; - using DeterminizeFstImplBase::GetFst; - using CacheBaseImpl>::GetCacheGc; - using CacheBaseImpl>::GetCacheLimit; - - DeterminizeFstImpl( - const Fst &fst, - const DeterminizeFstOptions &opts) - : DeterminizeFstImplBase(fst, opts), - delta_(opts.delta), - subsequential_label_(opts.subsequential_label), - increment_subsequential_label_(opts.increment_subsequential_label) { - if (opts.state_table) { - FSTERROR() << "DeterminizeFst: " - << "A state table can not be passed with transducer input"; - SetProperties(kError, kError); - return; - } - // Takes ownership of filter. - Init(GetFst(), fst::WrapUnique(opts.filter)); - } - - DeterminizeFstImpl(const DeterminizeFstImpl &impl) - : DeterminizeFstImplBase(impl), - delta_(impl.delta_), - subsequential_label_(impl.subsequential_label_), - increment_subsequential_label_(impl.increment_subsequential_label_) { - Init(GetFst(), nullptr); - } - - DeterminizeFstImpl *Copy() const override { - return new DeterminizeFstImpl(*this); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && (GetFst().Properties(kError, false) || - from_fst_->Properties(kError, false))) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - StateId ComputeStart() override { return from_fst_->Start(); } - - Weight ComputeFinal(StateId s) override { return from_fst_->Final(s); } - - void Expand(StateId s) override { - for (ArcIterator aiter(*from_fst_, s); !aiter.Done(); - aiter.Next()) { - CacheImpl::PushArc(s, aiter.Value()); - } - CacheImpl::SetArcs(s); - } - - private: - // Initialization of transducer determinization implementation, which is - // defined after DeterminizeFst since it calls it. - void Init(const Fst &fst, std::unique_ptr filter); - - float delta_; - Label subsequential_label_; - bool increment_subsequential_label_; - std::unique_ptr from_fst_; -}; - -} // namespace internal - -// Determinizes a weighted transducer. This version is a delayed -// FST. The result will be an equivalent FST that has the property -// that no state has two transitions with the same input label. -// For this algorithm, epsilon transitions are treated as regular -// symbols (cf. RmEpsilon). -// -// The transducer must be functional. The weights must be (weakly) left -// divisible (valid for TropicalWeight and LogWeight for instance) and be -// zero-sum-free if for all a, b: (Plus(a, b) == 0) => a = b = 0. -// -// Complexity: -// -// Determinizable: exponential (polynomial in the size of the output). -// Non-determinizable: does not terminate. -// -// The determinizable automata include all unweighted and all acyclic input. -// -// For more information, see: -// -// Mohri, M. 1997. Finite-state transducers in language and speech processing. -// Computational Linguistics 23(2): 269-311. -// -// This class attaches interface to implementation and handles reference -// counting, delegating most methods to ImplToFst. -template -class DeterminizeFst : public ImplToFst> { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - using Impl = internal::DeterminizeFstImplBase; - - friend class ArcIterator>; - friend class StateIterator>; - - template - friend class DeterminizeFstImpl; - - explicit DeterminizeFst(const Fst &fst) - : ImplToFst(CreateImpl(fst)) {} - - template - explicit DeterminizeFst( - const Fst &fst, - const DeterminizeFstOptions - &opts = - DeterminizeFstOptions()) - : ImplToFst(CreateImpl(fst, opts)) {} - - // This acceptor-only version additionally computes the distance to final - // states in the output if provided with those distances for the input; this - // is useful for e.g., computing the k-shortest unique paths. - template - DeterminizeFst( - const Fst &fst, const std::vector *in_dist, - std::vector *out_dist, - const DeterminizeFstOptions - &opts = - DeterminizeFstOptions()) - : ImplToFst( - std::make_shared>( - fst, in_dist, out_dist, opts)) { - if (!fst.Properties(kAcceptor, true)) { - FSTERROR() << "DeterminizeFst: " - << "Distance to final states computed for acceptors only"; - GetMutableImpl()->SetProperties(kError, kError); - } - } - - // See Fst<>::Copy() for doc. - DeterminizeFst(const DeterminizeFst &fst, bool safe = false) - : ImplToFst(safe ? std::shared_ptr(fst.GetImpl()->Copy()) - : fst.GetSharedImpl()) {} - - // Get a copy of this DeterminizeFst. See Fst<>::Copy() for further doc. - DeterminizeFst *Copy(bool safe = false) const override { - return new DeterminizeFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - static std::shared_ptr CreateImpl(const Fst &fst) { - using D = DefaultCommonDivisor; - using F = DefaultDeterminizeFilter; - using T = DefaultDeterminizeStateTable; - const DeterminizeFstOptions opts; - return CreateImpl(fst, opts); - } - - template - static std::shared_ptr CreateImpl( - const Fst &fst, - const DeterminizeFstOptions - &opts) { - if (fst.Properties(kAcceptor, true)) { - // Calls implementation for acceptors. - return std::make_shared< - internal::DeterminizeFsaImpl>( - fst, nullptr, nullptr, opts); - } else if (opts.type == DETERMINIZE_DISAMBIGUATE) { - if constexpr (IsPath::value) { - // Calls disambiguating implementation for non-functional transducers. - return std::make_shared>(fst, opts); - } else { - FSTERROR() << "DeterminizeFst: Weight needs to have the path " - << "property to disambiguate output: " << Weight::Type(); - // Return an error Impl. - const ConstFst empty_fst; - auto rv = std::make_shared>(empty_fst, opts); - rv->SetProperties(kError, kError); - return rv; - } - } else if (opts.type == DETERMINIZE_FUNCTIONAL) { - // Calls implementation for functional transducers. - return std::make_shared>(fst, opts); - } else { // opts.type == DETERMINIZE_NONFUNCTIONAL - // Calls implementation for non functional transducers; - return std::make_shared>(fst, opts); - } - } - - DeterminizeFst &operator=(const DeterminizeFst &) = delete; -}; - -namespace internal { - -// Initialization of transducer determinization implementation, which is defined -// after DeterminizeFst since it calls it. -template -void DeterminizeFstImpl::Init(const Fst &fst, - std::unique_ptr filter) { - // Mapper to an acceptor. - const ToFst to_fst(fst); - auto *to_filter = filter ? new ToFilter(to_fst, std::move(filter)) : nullptr; - // This recursive call terminates since it is to a (non-recursive) - // different constructor. - const CacheOptions copts(GetCacheGc(), GetCacheLimit()); - const DeterminizeFstOptions - dopts(copts, delta_, 0, DETERMINIZE_FUNCTIONAL, false, to_filter); - // Uses acceptor-only constructor to avoid template recursion. - const DeterminizeFst det_fsa(to_fst, nullptr, nullptr, dopts); - // Mapper back to transducer. - const FactorWeightOptions fopts( - CacheOptions(true, 0), delta_, kFactorFinalWeights, subsequential_label_, - subsequential_label_, increment_subsequential_label_, - increment_subsequential_label_); - const FactorWeightFst factored_fst(det_fsa, fopts); - from_fst_ = - std::make_unique(factored_fst, FromMapper(subsequential_label_)); -} - -} // namespace internal - -// Specialization for DeterminizeFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const DeterminizeFst &fst) - : CacheStateIterator>(fst, fst.GetMutableImpl()) {} -}; - -// Specialization for DeterminizeFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const DeterminizeFst &fst, StateId s) - : CacheArcIterator>(fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void DeterminizeFst::InitStateIterator( - StateIteratorData *data) const { - data->base = std::make_unique>>(*this); -} - -// Useful aliases when using StdArc. -using StdDeterminizeFst = DeterminizeFst; - -template -struct DeterminizeOptions { - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - float delta; // Quantization delta for subset weights. - Weight weight_threshold; // Pruning weight threshold. - StateId state_threshold; // Pruning state threshold. - Label subsequential_label; // Label used for residual final output. - DeterminizeType type; - bool increment_subsequential_label; // When creating several subsequential - // arcs at a given state, make their - // label distinct by incrementation? - - explicit DeterminizeOptions(float delta = kDelta, - Weight weight_threshold = Weight::Zero(), - StateId state_threshold = kNoStateId, - Label subsequential_label = 0, - DeterminizeType type = DETERMINIZE_FUNCTIONAL, - bool increment_subsequential_label = false) - : delta(delta), - weight_threshold(std::move(weight_threshold)), - state_threshold(state_threshold), - subsequential_label(subsequential_label), - type(type), - increment_subsequential_label(increment_subsequential_label) {} -}; - -// Determinizes a weighted transducer. This version writes the -// determinized Fst to an output MutableFst. The result will be an -// equivalent FST that has the property that no state has two -// transitions with the same input label. For this algorithm, epsilon -// transitions are treated as regular symbols (cf. RmEpsilon). -// -// The transducer must be functional. The weights must be (weakly) -// left divisible (valid for TropicalWeight and LogWeight). -// -// Complexity: -// -// Determinizable: exponential (polynomial in the size of the output) -// Non-determinizable: does not terminate -// -// The determinizable automata include all unweighted and all acyclic input. -template -void Determinize( - const Fst &ifst, MutableFst *ofst, - const DeterminizeOptions &opts = DeterminizeOptions()) { - using Weight = typename Arc::Weight; - DeterminizeFstOptions nopts; - nopts.delta = opts.delta; - nopts.subsequential_label = opts.subsequential_label; - nopts.type = opts.type; - nopts.increment_subsequential_label = opts.increment_subsequential_label; - nopts.gc_limit = 0; // Caches only the last state for fastest copy. - if (opts.weight_threshold != Weight::Zero() || - opts.state_threshold != kNoStateId) { - if constexpr (IsPath::value) { - if (ifst.Properties(kAcceptor, false)) { - std::vector idistance; - std::vector odistance; - ShortestDistance(ifst, &idistance, true); - DeterminizeFst dfst(ifst, &idistance, &odistance, nopts); - PruneOptions> popts( - opts.weight_threshold, opts.state_threshold, AnyArcFilter(), - &odistance); - Prune(dfst, ofst, popts); - } else { - *ofst = DeterminizeFst(ifst, nopts); - Prune(ofst, opts.weight_threshold, opts.state_threshold); - } - } else { - FSTERROR() << "Determinize: Weight needs to have the path " - << "property to use pruning options: " << Weight::Type(); - ofst->SetProperties(kError, kError); - } - } else { - *ofst = DeterminizeFst(ifst, nopts); - } -} - -} // namespace fst - -#endif // FST_DETERMINIZE_H_ diff --git a/contrib/fstlib/fst/dfs-visit.h b/contrib/fstlib/fst/dfs-visit.h deleted file mode 100644 index acc2a4b..0000000 --- a/contrib/fstlib/fst/dfs-visit.h +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Depth-first search visitation. See visit.h for more general search queue -// disciplines. - -#ifndef FST_DFS_VISIT_H_ -#define FST_DFS_VISIT_H_ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace fst { - -// Visitor Interface: class determining actions taken during a depth-first -// search-style visit. If any of the boolean member functions return false, the -// DFS is aborted by first calling FinishState() on all currently grey states -// and then calling FinishVisit(). -// -// This is similar to the more general visitor interface in visit.h, except -// that FinishState returns additional information appropriate only for a DFS -// and some methods names here are better suited to a DFS. -// -// template -// class Visitor { -// public: -// using StateId = typename Arc::StateId; -// -// Visitor(T *return_data); -// -// // Invoked before DFS visit. -// void InitVisit(const Fst &fst); -// -// // Invoked when state discovered (2nd arg is DFS tree root). -// bool InitState(StateId s, StateId root); -// -// // Invoked when tree arc to white/undiscovered state examined. -// bool TreeArc(StateId s, const Arc &arc); -// -// // Invoked when back arc to grey/unfinished state examined. -// bool BackArc(StateId s, const Arc &arc); -// -// // Invoked when forward or cross arc to black/finished state examined. -// bool ForwardOrCrossArc(StateId s, const Arc &arc); -// -// // Invoked when state finished ('s' is tree root, 'parent' is kNoStateId, -// // and 'arc' is nullptr). -// void FinishState(StateId s, StateId parent, const Arc *arc); -// -// // Invoked after DFS visit. -// void FinishVisit(); -// }; - -namespace internal { - -// An FST state's DFS stack state. -template -struct DfsState { - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - - DfsState(const FST &fst, StateId s) : state_id(s), arc_iter(fst, s) {} - - void *operator new(size_t size, MemoryPool> *pool) { - return pool->Allocate(); - } - - static void Destroy(DfsState *dfs_state, - MemoryPool> *pool) { - if (dfs_state) { - dfs_state->~DfsState(); - pool->Free(dfs_state); - } - } - - StateId state_id; // FST state. - ArcIterator arc_iter; // The corresponding arcs. -}; - -} // namespace internal - -// Performs depth-first visitation. Visitor class argument determines actions -// and contains any return data. ArcFilter determines arcs that are considered. -// If 'access_only' is true, performs visitation only to states accessible from -// the initial state. -// -// Note this is similar to Visit() in visit.h called with a LIFO queue, except -// this version has a Visitor class specialized and augmented for a DFS. -template -void DfsVisit(const FST &fst, Visitor *visitor, ArcFilter filter, - bool access_only = false) { - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - visitor->InitVisit(fst); - const auto start = fst.Start(); - if (start == kNoStateId) { - visitor->FinishVisit(); - return; - } - // An FST state's DFS status - enum class StateColor : uint8_t { - kWhite = 0, // Undiscovered. - kGrey = 1, // Discovered but unfinished. - kBlack = 2, // Finished. - }; - std::vector state_color; - std::stack *> state_stack; // DFS execution stack. - MemoryPool> state_pool; // Pool for DFSStates. - // Exact number of states if known, otherwise lower bound. - StateId nstates = fst.NumStatesIfKnown().value_or(start + 1); - const bool expanded = fst.Properties(kExpanded, false); - state_color.resize(nstates, StateColor::kWhite); - StateIterator siter(fst); - // Continue DFS while true. - bool dfs = true; - // Iterate over trees in DFS forest. - for (auto root = start; dfs && root < nstates;) { - state_color[root] = StateColor::kGrey; - state_stack.push(new (&state_pool) internal::DfsState(fst, root)); - dfs = visitor->InitState(root, root); - while (!state_stack.empty()) { - auto *dfs_state = state_stack.top(); - const auto s = dfs_state->state_id; - if (s >= static_cast(state_color.size())) { - nstates = s + 1; - state_color.resize(nstates, StateColor::kWhite); - } - ArcIterator &aiter = dfs_state->arc_iter; - if (!dfs || aiter.Done()) { - state_color[s] = StateColor::kBlack; - internal::DfsState::Destroy(dfs_state, &state_pool); - state_stack.pop(); - if (!state_stack.empty()) { - auto *parent_state = state_stack.top(); - auto &piter = parent_state->arc_iter; - visitor->FinishState(s, parent_state->state_id, &piter.Value()); - piter.Next(); - } else { - visitor->FinishState(s, kNoStateId, nullptr); - } - continue; - } - const auto &arc = aiter.Value(); - if (arc.nextstate >= - static_cast(state_color.size())) { - nstates = arc.nextstate + 1; - state_color.resize(nstates, StateColor::kWhite); - } - if (!filter(arc)) { - aiter.Next(); - continue; - } - const auto next_color = state_color[arc.nextstate]; - switch (next_color) { - case StateColor::kWhite: - dfs = visitor->TreeArc(s, arc); - if (!dfs) break; - state_color[arc.nextstate] = StateColor::kGrey; - state_stack.push(new (&state_pool) - internal::DfsState(fst, arc.nextstate)); - dfs = visitor->InitState(arc.nextstate, root); - break; - case StateColor::kGrey: - dfs = visitor->BackArc(s, arc); - aiter.Next(); - break; - case StateColor::kBlack: - dfs = visitor->ForwardOrCrossArc(s, arc); - aiter.Next(); - break; - } - } - if (access_only) break; - // Finds next tree root. - for (root = root == start ? 0 : root + 1; - root < nstates && state_color[root] != StateColor::kWhite; ++root) { - } - // Checks for a state beyond the largest known state. - if (!expanded && root == nstates) { - for (; !siter.Done(); siter.Next()) { - if (siter.Value() == nstates) { - ++nstates; - state_color.push_back(StateColor::kWhite); - break; - } - } - } - } - visitor->FinishVisit(); -} - -template -void DfsVisit(const Fst &fst, Visitor *visitor) { - DfsVisit(fst, visitor, AnyArcFilter()); -} - -} // namespace fst - -#endif // FST_DFS_VISIT_H_ diff --git a/contrib/fstlib/fst/difference.h b/contrib/fstlib/fst/difference.h deleted file mode 100644 index fe8be67..0000000 --- a/contrib/fstlib/fst/difference.h +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to compute the difference between two FSAs. - -#ifndef FST_DIFFERENCE_H_ -#define FST_DIFFERENCE_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -template >, - class Filter = SequenceComposeFilter, - class StateTable = - GenericComposeStateTable> -struct DifferenceFstOptions - : public ComposeFstOptions { - explicit DifferenceFstOptions(const CacheOptions &opts = CacheOptions(), - M *matcher1 = nullptr, M *matcher2 = nullptr, - Filter *filter = nullptr, - StateTable *state_table = nullptr) - : ComposeFstOptions(opts, matcher1, matcher2, - filter, state_table) {} -}; - -// Computes the difference between two FSAs. This version is a delayed FST. -// Only strings that are in the first automaton but not in second are retained -// in the result. -// -// The first argument must be an acceptor; the second argument must be an -// unweighted, epsilon-free, deterministic acceptor. One of the arguments must -// be label-sorted. -// -// Complexity: same as ComposeFst. -// -// Caveats: same as ComposeFst. -template -class DifferenceFst : public ComposeFst { - public: - using Arc = A; - using Weight = typename Arc::Weight; - using StateId = typename Arc::StateId; - - using ComposeFst::CreateBase1; - - // A - B = A ^ B'. - DifferenceFst(const Fst &fst1, const Fst &fst2, - const CacheOptions &opts = CacheOptions()) - : ComposeFst(CreateDifferenceImplWithCacheOpts(fst1, fst2, opts)) { - if (!fst1.Properties(kAcceptor, true)) { - FSTERROR() << "DifferenceFst: 1st argument not an acceptor"; - GetImpl()->SetProperties(kError, kError); - } - } - - template - DifferenceFst( - const Fst &fst1, const Fst &fst2, - const DifferenceFstOptions &opts) - : ComposeFst( - CreateDifferenceImplWithDifferenceOpts(fst1, fst2, opts)) { - if (!fst1.Properties(kAcceptor, true)) { - FSTERROR() << "DifferenceFst: 1st argument not an acceptor"; - GetImpl()->SetProperties(kError, kError); - } - } - - // See Fst<>::Copy() for doc. - DifferenceFst(const DifferenceFst &fst, bool safe = false) - : ComposeFst(fst, safe) {} - - // Get a copy of this DifferenceFst. See Fst<>::Copy() for further doc. - DifferenceFst *Copy(bool safe = false) const override { - return new DifferenceFst(*this, safe); - } - - private: - using Impl = internal::ComposeFstImplBase; - using ImplToFst::GetImpl; - - static std::shared_ptr CreateDifferenceImplWithCacheOpts( - const Fst &fst1, const Fst &fst2, const CacheOptions &opts) { - using RM = RhoMatcher>>; - ComplementFst cfst(fst2); - ComposeFstOptions copts( - CacheOptions(), new RM(fst1, MATCH_NONE), - new RM(cfst, MATCH_INPUT, ComplementFst::kRhoLabel)); - return CreateBase1(fst1, cfst, copts); - } - - template - static std::shared_ptr CreateDifferenceImplWithDifferenceOpts( - const Fst &fst1, const Fst &fst2, - const DifferenceFstOptions &opts) { - using RM = RhoMatcher; - ComplementFst cfst(fst2); - ComposeFstOptions copts(opts); - copts.matcher1 = new RM(fst1, MATCH_NONE, kNoLabel, MATCHER_REWRITE_ALWAYS, - opts.matcher1); - copts.matcher2 = new RM(cfst, MATCH_INPUT, ComplementFst::kRhoLabel, - MATCHER_REWRITE_ALWAYS, opts.matcher2); - return CreateBase1(fst1, cfst, copts); - } -}; - -// Specialization for DifferenceFst. -template -class StateIterator> - : public StateIterator> { - public: - explicit StateIterator(const DifferenceFst &fst) - : StateIterator>(fst) {} -}; - -// Specialization for DifferenceFst. -template -class ArcIterator> : public ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const DifferenceFst &fst, StateId s) - : ArcIterator>(fst, s) {} -}; - -using DifferenceOptions = ComposeOptions; - -// Useful alias when using StdArc. -using StdDifferenceFst = DifferenceFst; - -using DifferenceOptions = ComposeOptions; - -// Computes the difference between two FSAs. This version writes the difference -// to an output MutableFst. Only strings that are in the first automaton but not -// in the second are retained in the result. -// -// The first argument must be an acceptor; the second argument must be an -// unweighted, epsilon-free, deterministic acceptor. One of the arguments must -// be label-sorted. -// -// Complexity: same as Compose. -// -// Caveats: same as Compose. -template -void Difference(const Fst &ifst1, const Fst &ifst2, - MutableFst *ofst, - const DifferenceOptions &opts = DifferenceOptions()) { - using M = Matcher>; - // In each case, we cache only the last state for fastest copy. - switch (opts.filter_type) { - case AUTO_FILTER: { - CacheOptions nopts; - nopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, nopts); - break; - } - case SEQUENCE_FILTER: { - DifferenceFstOptions dopts; - dopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, dopts); - break; - } - case ALT_SEQUENCE_FILTER: { - DifferenceFstOptions> dopts; - dopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, dopts); - break; - } - case MATCH_FILTER: { - DifferenceFstOptions> dopts; - dopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, dopts); - break; - } - case NO_MATCH_FILTER: { - DifferenceFstOptions> dopts; - dopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, dopts); - break; - } - case NULL_FILTER: { - DifferenceFstOptions> dopts; - dopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, dopts); - break; - } - case TRIVIAL_FILTER: { - DifferenceFstOptions> dopts; - dopts.gc_limit = 0; - *ofst = DifferenceFst(ifst1, ifst2, dopts); - break; - } - } - if (opts.connect) Connect(ofst); -} - -} // namespace fst - -#endif // FST_DIFFERENCE_H_ diff --git a/contrib/fstlib/fst/disambiguate.h b/contrib/fstlib/fst/disambiguate.h deleted file mode 100644 index 1d60e27..0000000 --- a/contrib/fstlib/fst/disambiguate.h +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to disambiguate an FST. - -#ifndef FST_DISAMBIGUATE_H_ -#define FST_DISAMBIGUATE_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -template -struct DisambiguateOptions : public DeterminizeOptions { - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit DisambiguateOptions(float delta = kDelta, - Weight weight = Weight::Zero(), - StateId n = kNoStateId, Label label = 0) - : DeterminizeOptions(delta, std::move(weight), n, label, - DETERMINIZE_FUNCTIONAL) {} -}; - -namespace internal { - -// A determinization filter based on a subset element relation. The relation is -// assumed to be reflexive and symmetric. -template -class RelationDeterminizeFilter { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FilterState = IntegerFilterState; - using StateTuple = DeterminizeStateTuple; - using Subset = typename StateTuple::Subset; - using Element = typename StateTuple::Element; - using LabelMap = std::multimap>; - - // This is needed (e.g.) to go into the gallic domain for transducers; there - // is no need to rebind the relation since its use here only depends on the - // state IDs. - template - struct rebind { - using Other = RelationDeterminizeFilter; - }; - - explicit RelationDeterminizeFilter(const Fst &fst) - : fst_(fst.Copy()), - head_(nullptr), - r_(std::make_unique()), - s_(kNoStateId) {} - - RelationDeterminizeFilter(const Fst &fst, std::unique_ptr r, - std::vector *head = nullptr) - : fst_(fst.Copy()), head_(head), r_(std::move(r)), s_(kNoStateId) {} - - // This is needed, e.g., to go into the gallic domain for transducers. - template - RelationDeterminizeFilter(const Fst &fst, std::unique_ptr filter) - : fst_(fst.Copy()), - head_(filter->GetHeadStates()), - r_(std::move(*filter).GetRelation()), - s_(kNoStateId) {} - - // Copy constructor; the FST can be passed if it has been deep-copied. - RelationDeterminizeFilter(const RelationDeterminizeFilter &filter, - const Fst *fst = nullptr) - : fst_(fst ? fst->Copy() : filter.fst_->Copy()), - head_(nullptr), - r_(std::make_unique(*filter.r_)), - s_(kNoStateId) {} - - FilterState Start() const { return FilterState(fst_->Start()); } - - void SetState(StateId s, const StateTuple &tuple) { - if (s_ != s) { - s_ = s; - tuple_ = &tuple; - const auto head = tuple.filter_state.GetState(); - is_final_ = fst_->Final(head) != Weight::Zero(); - if (head_) { - if (head_->size() <= s) head_->resize(s + 1, kNoStateId); - (*head_)[s] = head; - } - } - } - - // Filters transition, possibly modifying label map. Returns true if arc is - // added to label map. - bool FilterArc(const Arc &arc, const Element &src_element, - const Element &dest_element, LabelMap *label_map) const; - - // Filters super-final transition, returning new final weight. - Weight FilterFinal(const Weight final_weight, const Element &element) const { - return is_final_ ? final_weight : Weight::Zero(); - } - - static uint64_t Properties(uint64_t props) { - return props & ~(kIDeterministic | kODeterministic); - } - - std::unique_ptr GetRelation() && { return std::move(r_); } - - std::vector *GetHeadStates() { return head_; } - - private: - // Pairs arc labels with state tuples with possible heads and empty subsets. - void InitLabelMap(LabelMap *label_map) const; - - std::unique_ptr> fst_; // Input FST. - std::vector *head_; // Head state for a given state, - // owned by the Disambiguator. - std::unique_ptr r_; // Relation compatible with inv. trans. fnc. - StateId s_; // Current state. - const StateTuple *tuple_; // Current tuple. - bool is_final_; // Is the current head state final? -}; - -template -bool RelationDeterminizeFilter::FilterArc( - const Arc &arc, const Element &src_element, const Element &dest_element, - LabelMap *label_map) const { - bool added = false; - if (label_map->empty()) InitLabelMap(label_map); - // Adds element to state tuple if element state is related to tuple head. - for (auto liter = label_map->lower_bound(arc.ilabel); - liter != label_map->end() && liter->first == arc.ilabel; ++liter) { - const auto &dest_tuple = liter->second.dest_tuple; - const auto dest_head = dest_tuple->filter_state.GetState(); - if ((*r_)(dest_element.state_id, dest_head)) { - dest_tuple->subset.push_front(dest_element); - added = true; - } - } - return added; -} - -template -void RelationDeterminizeFilter::InitLabelMap( - LabelMap *label_map) const { - const auto src_head = tuple_->filter_state.GetState(); - Label label = kNoLabel; - StateId nextstate = kNoStateId; - for (ArcIterator> aiter(*fst_, src_head); !aiter.Done(); - aiter.Next()) { - const auto &arc = aiter.Value(); - // Continues if multiarc. - if (arc.ilabel == label && arc.nextstate == nextstate) continue; - DeterminizeArc det_arc(arc); - det_arc.dest_tuple->filter_state = FilterState(arc.nextstate); - label_map->emplace(arc.ilabel, std::move(det_arc)); - label = arc.ilabel; - nextstate = arc.nextstate; - } -} - -// Helper class to disambiguate an FST via Disambiguate(). -template -class Disambiguator { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - // IDs arcs with state ID and arc position. Arc position -1 indicates final - // (super-final transition). - using ArcId = std::pair; - - Disambiguator() : error_(false) {} - - void Disambiguate( - const Fst &ifst, MutableFst *ofst, - const DisambiguateOptions &opts = DisambiguateOptions()) { - VectorFst sfst(ifst); - Connect(&sfst); - ArcSort(&sfst, ArcCompare()); - PreDisambiguate(sfst, ofst, opts); - ArcSort(ofst, ArcCompare()); - FindAmbiguities(*ofst); - RemoveSplits(ofst); - MarkAmbiguities(); - RemoveAmbiguities(ofst); - if (error_) ofst->SetProperties(kError, kError); - } - - private: - // Comparison functor for comparing input labels and next states of arcs. This - // sort order facilitates the predisambiguation. - class ArcCompare { - public: - bool operator()(const Arc &arc1, const Arc &arc2) const { - return arc1.ilabel < arc2.ilabel || - (arc1.ilabel == arc2.ilabel && arc1.nextstate < arc2.nextstate); - } - - uint64_t Properties(uint64_t props) const { - return (props & kArcSortProperties) | kILabelSorted | - (props & kAcceptor ? kOLabelSorted : 0); - } - }; - - // Comparison functor for comparing transitions represented by their arc ID. - // This sort order facilitates ambiguity detection. - class ArcIdCompare { - public: - explicit ArcIdCompare(const std::vector &head) : head_(head) {} - - bool operator()(const ArcId &a1, const ArcId &a2) const { - // Sort first by source head state... - const auto src1 = a1.first; - const auto src2 = a2.first; - const auto head1 = head_[src1]; - const auto head2 = head_[src2]; - if (head1 < head2) return true; - if (head2 < head1) return false; - // ...then by source state... - if (src1 < src2) return true; - if (src2 < src1) return false; - // ...then by position. - return a1.second < a2.second; - } - - private: - const std::vector &head_; - }; - - // A relation that determines if two states share a common future. - class CommonFuture { - public: - using StateTable = GenericComposeStateTable; - using StateTuple = typename StateTable::StateTuple; - - // Needed for compilation with DeterminizeRelationFilter. - CommonFuture() { - FSTERROR() << "Disambiguate::CommonFuture: FST not provided"; - } - - explicit CommonFuture(const Fst &ifst) { - using M = Matcher>; - ComposeFstOptions> opts; - // Ensures composition is between acceptors. - const bool trans = ifst.Properties(kNotAcceptor, true); - const auto *fsa = - trans ? new ProjectFst(ifst, ProjectType::INPUT) : &ifst; - opts.state_table = new StateTable(*fsa, *fsa); - const ComposeFst cfst(*fsa, *fsa, opts); - std::vector coaccess; - uint64_t props = 0; - SccVisitor scc_visitor(nullptr, nullptr, &coaccess, &props); - DfsVisit(cfst, &scc_visitor); - for (StateId s = 0; s < coaccess.size(); ++s) { - if (coaccess[s]) { - related_.insert(opts.state_table->Tuple(s).StatePair()); - } - } - if (trans) delete fsa; - } - - bool operator()(const StateId s1, StateId s2) const { - return related_.count(std::make_pair(s1, s2)) > 0; - } - - private: - // States s1 and s2 resp. are in this relation iff they there is a - // path from s1 to a final state that has the same label as some - // path from s2 to a final state. - std::set> related_; - }; - - using ArcIdMap = std::multimap; - - // Inserts candidate into the arc ID map. - inline void InsertCandidate(StateId s1, StateId s2, const ArcId &a1, - const ArcId &a2) { - candidates_->insert(head_[s1] > head_[s2] ? std::make_pair(a1, a2) - : std::make_pair(a2, a1)); - } - - // Returns the arc corresponding to ArcId a. - static Arc GetArc(const Fst &fst, ArcId aid) { - if (aid.second == -1) { // Returns super-final transition. - return Arc(kNoLabel, kNoLabel, fst.Final(aid.first), kNoStateId); - } else { - ArcIterator> aiter(fst, aid.first); - aiter.Seek(aid.second); - return aiter.Value(); - } - } - - // Outputs an equivalent FST whose states are subsets of states that have a - // future path in common. - void PreDisambiguate(const ExpandedFst &ifst, MutableFst *ofst, - const DisambiguateOptions &opts); - - // Finds transitions that are ambiguous candidates in the result of - // PreDisambiguate. - void FindAmbiguities(const ExpandedFst &fst); - - // Finds transition pairs that are ambiguous candidates from two specified - // source states. - void FindAmbiguousPairs(const ExpandedFst &fst, StateId s1, StateId s2); - - // Marks ambiguous transitions to be removed. - void MarkAmbiguities(); - - // Deletes spurious ambiguous transitions (due to quantization). - void RemoveSplits(MutableFst *ofst); - - // Deletes actual ambiguous transitions. - void RemoveAmbiguities(MutableFst *ofst); - - // States s1 and s2 are in this relation iff there is a path from the initial - // state to s1 that has the same label as some path from the initial state to - // s2. We store only state pairs s1, s2 such that s1 <= s2. - std::set> coreachable_; - - // Queue of disambiguation-related states to be processed. We store only - // state pairs s1, s2 such that s1 <= s2. - std::list> queue_; - - // Head state in the pre-disambiguation for a given state. - std::vector head_; - - // Maps from a candidate ambiguous arc A to each ambiguous candidate arc B - // with the same label and destination state as A, whose source state s' is - // coreachable with the source state s of A, and for which head(s') < head(s). - std::unique_ptr candidates_; - - // Set of ambiguous transitions to be removed. - std::set ambiguous_; - - // States to merge due to quantization issues. - std::unique_ptr> merge_; - // Marks error condition. - bool error_; - - Disambiguator(const Disambiguator &) = delete; - Disambiguator &operator=(const Disambiguator &) = delete; -}; - -template -void Disambiguator::PreDisambiguate(const ExpandedFst &ifst, - MutableFst *ofst, - const DisambiguateOptions &opts) { - using CommonDivisor = DefaultCommonDivisor; - using Filter = RelationDeterminizeFilter; - // Subset elements with states s1 and s2 (resp.) are in this relation iff they - // there is a path from s1 to a final state that has the same label as some - // path from s2 to a final state. - auto common_future = std::make_unique(ifst); - DeterminizeFstOptions nopts; - nopts.delta = opts.delta; - nopts.subsequential_label = opts.subsequential_label; - nopts.filter = new Filter(ifst, std::move(common_future), &head_); - // Determinization takes ownership of the filter itself. - nopts.gc_limit = 0; // Cache only the last state for fastest copy. - if (opts.weight_threshold != Weight::Zero() || - opts.state_threshold != kNoStateId) { - if constexpr (IsPath::value) { - /* TODO(riley): fails regression test; understand why - if (ifst.Properties(kAcceptor, true)) { - std::vector idistance, odistance; - ShortestDistance(ifst, &idistance, true); - DeterminizeFst dfst(ifst, &idistance, &odistance, nopts); - PruneOptions< Arc, AnyArcFilter> popts(opts.weight_threshold, - opts.state_threshold, - AnyArcFilter(), - &odistance); - Prune(dfst, ofst, popts); - } else */ - { - *ofst = DeterminizeFst(ifst, nopts); - Prune(ofst, opts.weight_threshold, opts.state_threshold); - } - } else { - FSTERROR() << "Disambiguate: Weight must have path property to use " - << "pruning options: " << Weight::Type(); - error_ = true; - } - } else { - *ofst = DeterminizeFst(ifst, nopts); - } - head_.resize(ofst->NumStates(), kNoStateId); -} - -template -void Disambiguator::FindAmbiguities(const ExpandedFst &fst) { - if (fst.Start() == kNoStateId) return; - candidates_ = std::make_unique(ArcIdCompare(head_)); - const auto start_pr = std::make_pair(fst.Start(), fst.Start()); - coreachable_.insert(start_pr); - queue_.push_back(start_pr); - while (!queue_.empty()) { - const auto &pr = queue_.front(); - const auto s1 = pr.first; - const auto s2 = pr.second; - queue_.pop_front(); - FindAmbiguousPairs(fst, s1, s2); - } -} - -template -void Disambiguator::FindAmbiguousPairs(const ExpandedFst &fst, - StateId s1, StateId s2) { - if (fst.NumArcs(s2) > fst.NumArcs(s1)) FindAmbiguousPairs(fst, s2, s1); - SortedMatcher> matcher(fst, MATCH_INPUT); - matcher.SetState(s2); - for (ArcIterator> aiter(fst, s1); !aiter.Done(); aiter.Next()) { - const auto &arc1 = aiter.Value(); - const ArcId a1(s1, aiter.Position()); - if (matcher.Find(arc1.ilabel)) { - for (; !matcher.Done(); matcher.Next()) { - const auto &arc2 = matcher.Value(); - // Continues on implicit epsilon match. - if (arc2.ilabel == kNoLabel) continue; - const ArcId a2(s2, matcher.Position()); - // Actual transition is ambiguous. - if (s1 != s2 && arc1.nextstate == arc2.nextstate) { - InsertCandidate(s1, s2, a1, a2); - } - const auto spr = arc1.nextstate <= arc2.nextstate - ? std::make_pair(arc1.nextstate, arc2.nextstate) - : std::make_pair(arc2.nextstate, arc1.nextstate); - // Not already marked as coreachable? - if (coreachable_.insert(spr).second) { - // Only possible if state split by quantization issues. - if (spr.first != spr.second && - head_[spr.first] == head_[spr.second]) { - if (!merge_) { - merge_ = std::make_unique>(fst.NumStates(), - kNoStateId); - merge_->MakeAllSet(fst.NumStates()); - } - merge_->Union(spr.first, spr.second); - } else { - queue_.push_back(spr); - } - } - } - } - } - // Super-final transition is ambiguous. - if (s1 != s2 && fst.Final(s1) != Weight::Zero() && - fst.Final(s2) != Weight::Zero()) { - const ArcId a1(s1, -1); - const ArcId a2(s2, -1); - InsertCandidate(s1, s2, a1, a2); - } -} - -template -void Disambiguator::MarkAmbiguities() { - if (!candidates_) return; - for (auto it = candidates_->begin(); it != candidates_->end(); ++it) { - const auto a = it->first; - const auto b = it->second; - // If b is not to be removed, then a is. - if (ambiguous_.count(b) == 0) ambiguous_.insert(a); - } - coreachable_.clear(); - candidates_.reset(); -} - -template -void Disambiguator::RemoveSplits(MutableFst *ofst) { - if (!merge_) return; - // Merges split states to remove spurious ambiguities. - for (StateIterator> siter(*ofst); !siter.Done(); - siter.Next()) { - for (MutableArcIterator> aiter(ofst, siter.Value()); - !aiter.Done(); aiter.Next()) { - auto arc = aiter.Value(); - const auto nextstate = merge_->FindSet(arc.nextstate); - if (nextstate != arc.nextstate) { - arc.nextstate = nextstate; - aiter.SetValue(arc); - } - } - } - // Repeats search for actual ambiguities on modified FST. - coreachable_.clear(); - merge_.reset(); - candidates_.reset(); - FindAmbiguities(*ofst); - if (merge_) { // Shouldn't get here; sanity test. - FSTERROR() << "Disambiguate: Unable to remove spurious ambiguities"; - error_ = true; - return; - } -} - -template -void Disambiguator::RemoveAmbiguities(MutableFst *ofst) { - if (ambiguous_.empty()) return; - // Adds dead state to redirect ambiguous transitions to be removed. - const auto dead = ofst->AddState(); - for (auto it = ambiguous_.begin(); it != ambiguous_.end(); ++it) { - const auto pos = it->second; - if (pos >= 0) { // Actual transition. - MutableArcIterator> aiter(ofst, it->first); - aiter.Seek(pos); - auto arc = aiter.Value(); - arc.nextstate = dead; - aiter.SetValue(arc); - } else { // Super-final transition. - ofst->SetFinal(it->first, Weight::Zero()); - } - } - Connect(ofst); - ambiguous_.clear(); -} - -} // namespace internal - -// Disambiguates a weighted FST. This version writes the disambiguated FST to an -// output MutableFst. The result will be an equivalent FST that has the -// property that there are not two distinct paths from the initial state to a -// final state with the same input labeling. -// -// The weights must be (weakly) left divisible (valid for Tropical and -// LogWeight). -// -// Complexity: -// -// Disambiguable: exponential (polynomial in the size of the output). -// Non-disambiguable: does not terminate. -// -// The disambiguable transducers include all automata and functional transducers -// that are unweighted or that are acyclic or that are unambiguous. -// -// For more information, see: -// -// Mohri, M. and Riley, M. 2015. On the disambiguation of weighted automata. -// In CIAA, pages 263-278. -template -void Disambiguate( - const Fst &ifst, MutableFst *ofst, - const DisambiguateOptions &opts = DisambiguateOptions()) { - internal::Disambiguator disambiguator; - disambiguator.Disambiguate(ifst, ofst, opts); -} - -} // namespace fst - -#endif // FST_DISAMBIGUATE_H_ diff --git a/contrib/fstlib/fst/edit-fst.h b/contrib/fstlib/fst/edit-fst.h deleted file mode 100644 index 9b84105..0000000 --- a/contrib/fstlib/fst/edit-fst.h +++ /dev/null @@ -1,723 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// An FST implementation that allows non-destructive edit operations on an -// existing FST. -// -// The EditFst class enables non-destructive edit operations on a wrapped -// ExpandedFst. The implementation uses copy-on-write semantics at the node -// level: if a user has an underlying FST on which they want to perform a -// relatively small number of edits (read: mutations), then this implementation -// will copy the edited node to an internal MutableFst and perform any edits in -// situ on that copied node. This class supports all the methods of MutableFst -// except for DeleteStates(const std::vector &); thus, new nodes may -// also be -// added, and one may add transitions from existing nodes of the wrapped FST to -// new nodes. -// -// N.B.: The documentation for Fst::Copy(true) says that its behavior is -// undefined if invoked on an FST that has already been accessed. This class -// requires that the Fst implementation it wraps provides consistent, reliable -// behavior when its Copy(true) method is invoked, where consistent means -// the graph structure, graph properties and state numbering and do not change. -// VectorFst and CompactFst, for example, are both well-behaved in this regard. - -#ifndef FST_EDIT_FST_H_ -#define FST_EDIT_FST_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { -namespace internal { - -// The EditFstData class is a container for all mutable data for EditFstImpl; -// also, this class provides most of the actual implementation of what EditFst -// does (that is, most of EditFstImpl's methods delegate to methods in this, the -// EditFstData class). Instances of this class are reference-counted and can be -// shared between otherwise independent EditFstImpl instances. This scheme -// allows EditFstImpl to implement the thread-safe, copy-on-write semantics -// required by Fst::Copy(true). -// -// template parameters: -// A: the type of arc to use -// WrappedFstT: the type of FST wrapped by the EditFst instance that -// this EditFstData instance is backing -// MutableFstT: the type of mutable FST to use internally for edited states; -// crucially, MutableFstT::Copy(false) *must* yield an FST that is -// thread-safe for reading (VectorFst, for example, has this property) -template , - typename MutableFstT = VectorFst> -class EditFstData { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - EditFstData() : num_new_states_(0) {} - - EditFstData(const EditFstData &other) - : edits_(other.edits_), - external_to_internal_ids_(other.external_to_internal_ids_), - edited_final_weights_(other.edited_final_weights_), - num_new_states_(other.num_new_states_) {} - - ~EditFstData() = default; - - static EditFstData *Read(std::istream &strm, const FstReadOptions &opts); - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const { - // Serializes all private data members of this class. - FstWriteOptions edits_opts(opts); - edits_opts.write_header = true; // Forces writing contained header. - edits_.Write(strm, edits_opts); - WriteType(strm, external_to_internal_ids_); - WriteType(strm, edited_final_weights_); - WriteType(strm, num_new_states_); - if (!strm) { - LOG(ERROR) << "EditFstData::Write: Write failed: " << opts.source; - return false; - } - return true; - } - - StateId NumNewStates() const { return num_new_states_; } - - // Accessor methods for the FST holding edited states. - StateId EditedStart() const { return edits_.Start(); } - - Weight Final(StateId s, const WrappedFstT *wrapped) const { - auto final_weight_it = GetFinalWeightIterator(s); - if (final_weight_it == NotInFinalWeightMap()) { - const auto it = GetEditedIdMapIterator(s); - return it == NotInEditedMap() ? wrapped->Final(s) - : edits_.Final(it->second); - } else { - return final_weight_it->second; - } - } - - size_t NumArcs(StateId s, const WrappedFstT *wrapped) const { - const auto it = GetEditedIdMapIterator(s); - return it == NotInEditedMap() ? wrapped->NumArcs(s) - : edits_.NumArcs(it->second); - } - - size_t NumInputEpsilons(StateId s, const WrappedFstT *wrapped) const { - const auto it = GetEditedIdMapIterator(s); - return it == NotInEditedMap() ? wrapped->NumInputEpsilons(s) - : edits_.NumInputEpsilons(it->second); - } - - size_t NumOutputEpsilons(StateId s, const WrappedFstT *wrapped) const { - const auto it = GetEditedIdMapIterator(s); - return it == NotInEditedMap() ? wrapped->NumOutputEpsilons(s) - : edits_.NumOutputEpsilons(it->second); - } - - void SetEditedProperties(uint64_t props, uint64_t mask) { - edits_.SetProperties(props, mask); - } - - // Non-const MutableFst operations. - - // Sets the start state for this FST. - void SetStart(StateId s) { edits_.SetStart(s); } - - // Sets the final state for this FST. - Weight SetFinal(StateId s, Weight weight, const WrappedFstT *wrapped) { - const auto old_weight = Final(s, wrapped); - const auto it = GetEditedIdMapIterator(s); - // If we haven't already edited state s, don't add it to edited_ (which can - // be expensive if s has many transitions); just use the - // edited_final_weights_ map. - if (it == NotInEditedMap()) { - edited_final_weights_[s] = weight; - } else { - edits_.SetFinal(GetEditableInternalId(s, wrapped), weight); - } - return old_weight; - } - - // Adds a new state to this FST. - StateId AddState(StateId curr_num_states) { - external_to_internal_ids_[curr_num_states] = edits_.AddState(); - ++num_new_states_; - return curr_num_states; - } - - // Adds new states to this FST. - void AddStates(StateId curr_num_states, size_t n) { - for (size_t i = 0; i < n; ++i) { - curr_num_states = AddState(curr_num_states); - } - } - - // Adds the specified arc to the specified state of this FST. - const Arc *AddArc(StateId s, const Arc &arc, const WrappedFstT *wrapped) { - const auto internal_id = GetEditableInternalId(s, wrapped); - const auto num_arcs = edits_.NumArcs(internal_id); - ArcIterator arc_it(edits_, internal_id); - const Arc *prev_arc = nullptr; - if (num_arcs > 0) { - // Grabs the final arc associated with this state in edits_. - arc_it.Seek(num_arcs - 1); - prev_arc = &(arc_it.Value()); - } - edits_.AddArc(internal_id, arc); - return prev_arc; - } - - void DeleteStates() { - edits_.DeleteStates(); - num_new_states_ = 0; - external_to_internal_ids_.clear(); - edited_final_weights_.clear(); - } - - // Removes all but the first n outgoing arcs of the specified state. - void DeleteArcs(StateId s, size_t n, const WrappedFstT *wrapped) { - edits_.DeleteArcs(GetEditableInternalId(s, wrapped), n); - } - - // Removes all outgoing arcs from the specified state. - void DeleteArcs(StateId s, const WrappedFstT *wrapped) { - edits_.DeleteArcs(GetEditableInternalId(s, wrapped)); - } - - // End methods for non-const MutableFst operations. - - // Provides information for the generic arc iterator. - void InitArcIterator(StateId s, ArcIteratorData *data, - const WrappedFstT *wrapped) const { - const auto it = GetEditedIdMapIterator(s); - if (it == NotInEditedMap()) { - VLOG(3) << "EditFstData::InitArcIterator: iterating on state " << s - << " of original FST"; - wrapped->InitArcIterator(s, data); - } else { - VLOG(2) << "EditFstData::InitArcIterator: iterating on edited state " << s - << " (internal state ID: " << it->second << ")"; - edits_.InitArcIterator(it->second, data); - } - } - - // Provides information for the generic mutable arc iterator. - void InitMutableArcIterator(StateId s, MutableArcIteratorData *data, - const WrappedFstT *wrapped) { - data->base = std::make_unique>( - &edits_, GetEditableInternalId(s, wrapped)); - } - - // Prints out the map from external to internal state IDs (for debugging - // purposes). - void PrintMap() { - for (auto it = external_to_internal_ids_.begin(); it != NotInEditedMap(); - ++it) { - LOG(INFO) << "(external,internal)=(" << it->first << "," << it->second - << ")"; - } - } - - private: - // Returns the iterator of the map from external to internal state IDs - // of edits_ for the specified external state IDs. - typename std::unordered_map::const_iterator - GetEditedIdMapIterator(StateId s) const { - return external_to_internal_ids_.find(s); - } - - typename std::unordered_map::const_iterator - NotInEditedMap() const { - return external_to_internal_ids_.end(); - } - - typename std::unordered_map::const_iterator - GetFinalWeightIterator(StateId s) const { - return edited_final_weights_.find(s); - } - - typename std::unordered_map::const_iterator - NotInFinalWeightMap() const { - return edited_final_weights_.end(); - } - - // Returns the internal state ID of the specified external ID if the state has - // already been made editable, or else copies the state from wrapped_ to - // edits_ and returns the state ID of the newly editable state in edits_. - StateId GetEditableInternalId(StateId s, const WrappedFstT *wrapped) { - auto id_map_it = GetEditedIdMapIterator(s); - if (id_map_it == NotInEditedMap()) { - StateId new_internal_id = edits_.AddState(); - VLOG(2) << "EditFstData::GetEditableInternalId: editing state " << s - << " of original FST; new internal state id:" << new_internal_id; - external_to_internal_ids_[s] = new_internal_id; - for (ArcIterator> arc_iterator(*wrapped, s); - !arc_iterator.Done(); arc_iterator.Next()) { - edits_.AddArc(new_internal_id, arc_iterator.Value()); - } - // Copies the final weight. - auto final_weight_it = GetFinalWeightIterator(s); - if (final_weight_it == NotInFinalWeightMap()) { - edits_.SetFinal(new_internal_id, wrapped->Final(s)); - } else { - edits_.SetFinal(new_internal_id, final_weight_it->second); - edited_final_weights_.erase(s); - } - return new_internal_id; - } else { - return id_map_it->second; - } - } - - // A mutable FST (by default, a VectorFst) to contain new states, and/or - // copies of states from a wrapped ExpandedFst that have been modified in - // some way. - MutableFstT edits_; - // A mapping from external state IDs to the internal IDs of states that - // appear in edits_. - std::unordered_map external_to_internal_ids_; - // A mapping from external state IDs to final state weights assigned to - // those states. The states in this map are *only* those whose final weight - // has been modified; if any other part of the state has been modified, - // the entire state is copied to edits_, and all modifications reside there. - std::unordered_map edited_final_weights_; - // The number of new states added to this mutable FST impl, which is <= the - // number of states in edits_ (since edits_ contains both edited *and* new - // states). - StateId num_new_states_; -}; - -// EditFstData method implementations: just the Read method. -template -EditFstData * -EditFstData::Read(std::istream &strm, - const FstReadOptions &opts) { - auto data = fst::make_unique_for_overwrite(); - // Next read in MutabelFstT machine that stores edits - FstReadOptions edits_opts(opts); - // Contained header was written out, so read it in. - edits_opts.header = nullptr; - // Because our internal representation of edited states is a solid object - // of type MutableFstT (defaults to VectorFst) and not a pointer, - // and because the static Read method allocates a new object on the heap, - // we need to call Read, check if there was a failure, use - // MutableFstT::operator= to assign the object (not the pointer) to the - // edits_ data member (which will increase the ref count by 1 on the impl) - // and, finally, delete the heap-allocated object. - std::unique_ptr edits(MutableFstT::Read(strm, edits_opts)); - if (!edits) return nullptr; - data->edits_ = *edits; - edits.reset(); - // Finally, reads in rest of private data members. - ReadType(strm, &data->external_to_internal_ids_); - ReadType(strm, &data->edited_final_weights_); - ReadType(strm, &data->num_new_states_); - if (!strm) { - LOG(ERROR) << "EditFst::Read: read failed: " << opts.source; - return nullptr; - } - return data.release(); -} - -// This class enables non-destructive edit operations on a wrapped ExpandedFst. -// The implementation uses copy-on-write semantics at the node level: if a user -// has an underlying FST on which they want to perform a relatively small -// number of edits (read: mutations), then this implementation will copy the -// edited node to an internal MutableFst and perform any edits in situ on that -// copied node. This class supports all the methods of MutableFst except for -// DeleteStates(const std::vector &); thus, new nodes may also be -// added, and -// one may add transitions from existing nodes of the wrapped FST to new nodes. -// -// template parameters: -// A: the type of arc to use -// WrappedFstT: the type of FST wrapped by the EditFst instance that -// this EditFstImpl instance is backing -// MutableFstT: the type of mutable FST to use internally for edited states; -// crucially, MutableFstT::Copy(false) must yield an FST that is -// thread-safe for reading (VectorFst, for example, has this property) -template , - typename MutableFstT = VectorFst> -class EditFstImpl : public FstImpl { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - using FstImpl::WriteHeader; - - // Constructs an editable FST implementation with no states. Effectively, this - // initially-empty FST will in every way mimic the behavior of a - // VectorFst---more precisely, a VectorFstImpl instance---but with slightly - // slower performance (by a constant factor), due to the fact that - // this class maintains a mapping between external state id's and - // their internal equivalents. - EditFstImpl() : wrapped_(new MutableFstT()) { - FstImpl::SetType("edit"); - InheritPropertiesFromWrapped(); - data_ = std::make_shared>(); - } - - // Wraps the specified ExpandedFst. This constructor requires that the - // specified Fst is an ExpandedFst instance. This requirement is only enforced - // at runtime. (See below for the reason.) - // - // This library uses the pointer-to-implementation or "PIMPL" design pattern. - // In particular, to make it convenient to bind an implementation class to its - // interface, there are a pair of template "binder" classes, one for immutable - // and one for mutable FSTs (ImplToFst and ImplToMutableFst, respectively). - // As it happens, the API for the ImplToMutableFst class requires that - // the implementation class--the template parameter "I"--have a constructor - // taking a const Fst reference. Accordingly, the constructor here must - // perform a down_cast to the WrappedFstT type required by EditFst and - // therefore EditFstImpl. - explicit EditFstImpl(const Fst &wrapped) - : wrapped_(down_cast(wrapped.Copy())) { - FstImpl::SetType("edit"); - data_ = std::make_shared>(); - // have edits_ inherit all properties from wrapped_ - data_->SetEditedProperties(wrapped_->Properties(kFstProperties, false), - kFstProperties); - InheritPropertiesFromWrapped(); - } - - // A copy constructor for this implementation class, used to implement - // the Copy() method of the Fst interface. - EditFstImpl(const EditFstImpl &impl) - : FstImpl(), - wrapped_(down_cast(impl.wrapped_->Copy(true))), - data_(impl.data_) { - SetProperties(impl.Properties()); - } - - // const Fst/ExpandedFst operations, declared in the Fst and ExpandedFst - // interfaces - StateId Start() const { - const auto edited_start = data_->EditedStart(); - return edited_start == kNoStateId ? wrapped_->Start() : edited_start; - } - - Weight Final(StateId s) const { return data_->Final(s, wrapped_.get()); } - - size_t NumArcs(StateId s) const { return data_->NumArcs(s, wrapped_.get()); } - - size_t NumInputEpsilons(StateId s) const { - return data_->NumInputEpsilons(s, wrapped_.get()); - } - - size_t NumOutputEpsilons(StateId s) const { - return data_->NumOutputEpsilons(s, wrapped_.get()); - } - - StateId NumStates() const { - return wrapped_->NumStates() + data_->NumNewStates(); - } - - static EditFstImpl *Read(std::istream &strm, const FstReadOptions &opts); - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const { - FstHeader hdr; - hdr.SetStart(Start()); - hdr.SetNumStates(NumStates()); - FstWriteOptions header_opts(opts); - // Allows the contained FST to hold any symbols. - header_opts.write_isymbols = false; - header_opts.write_osymbols = false; - WriteHeader(strm, header_opts, kFileVersion, &hdr); - // Serializes the wrapped FST to stream. - FstWriteOptions wrapped_opts(opts); - // Forces writing the contained header. - wrapped_opts.write_header = true; - wrapped_->Write(strm, wrapped_opts); - data_->Write(strm, opts); - strm.flush(); - if (!strm) { - LOG(ERROR) << "EditFst::Write: Write failed: " << opts.source; - return false; - } - return true; - } - - // Sets the start state for this FST. - void SetStart(StateId s) { - MutateCheck(); - data_->SetStart(s); - SetProperties(SetStartProperties(FstImpl::Properties())); - } - - // Sets the final state for this FST. - void SetFinal(StateId s, Weight weight) { - MutateCheck(); - Weight old_weight = data_->SetFinal(s, weight, wrapped_.get()); - SetProperties( - SetFinalProperties(FstImpl::Properties(), old_weight, weight)); - } - - // Adds a new state to this FST. - StateId AddState() { - MutateCheck(); - SetProperties(AddStateProperties(FstImpl::Properties())); - return data_->AddState(NumStates()); - } - - // Adds new states to this FST. - void AddStates(size_t n) { - MutateCheck(); - SetProperties(AddStateProperties(FstImpl::Properties())); - return data_->AddStates(NumStates(), n); - } - - // Adds the specified arc to the specified state of this FST. - void AddArc(StateId s, const Arc &arc) { - MutateCheck(); - const auto *prev_arc = data_->AddArc(s, arc, wrapped_.get()); - SetProperties( - AddArcProperties(FstImpl::Properties(), s, arc, prev_arc)); - } - - void DeleteStates(const std::vector &dstates) { - FSTERROR() << ": EditFstImpl::DeleteStates(const std::vector&): " - << " not implemented"; - SetProperties(kError, kError); - } - - // Deletes all states in this FST. - void DeleteStates(); - - // Removes all but the first n outgoing arcs of the specified state. - void DeleteArcs(StateId s, size_t n) { - MutateCheck(); - data_->DeleteArcs(s, n, wrapped_.get()); - SetProperties(DeleteArcsProperties(FstImpl::Properties())); - } - - // Removes all outgoing arcs from the specified state. - void DeleteArcs(StateId s) { - MutateCheck(); - data_->DeleteArcs(s, wrapped_.get()); - SetProperties(DeleteArcsProperties(FstImpl::Properties())); - } - - void ReserveStates(StateId s) {} - - void ReserveArcs(StateId s, size_t n) {} - - // Ends non-const MutableFst operations. - - // Provides information for the generic state iterator. - void InitStateIterator(StateIteratorData *data) const { - data->base = nullptr; - data->nstates = NumStates(); - } - - // Provides information for the generic arc iterator. - void InitArcIterator(StateId s, ArcIteratorData *data) const { - data_->InitArcIterator(s, data, wrapped_.get()); - } - - // Provides information for the generic mutable arc iterator. - void InitMutableArcIterator(StateId s, MutableArcIteratorData *data) { - MutateCheck(); - data_->InitMutableArcIterator(s, data, wrapped_.get()); - } - - private: - // Properties always true of this FST class. - static constexpr uint64_t kStaticProperties = kExpanded | kMutable; - // Current file format version. - static constexpr int kFileVersion = 2; - // Minimum file format version supported - static constexpr int kMinFileVersion = 2; - - // Causes this FST to inherit all the properties from its wrapped FST, except - // for the two properties that always apply to EditFst instances: kExpanded - // and kMutable. - void InheritPropertiesFromWrapped() { - SetProperties(wrapped_->Properties(kCopyProperties, false) | - kStaticProperties); - SetInputSymbols(wrapped_->InputSymbols()); - SetOutputSymbols(wrapped_->OutputSymbols()); - } - - // This method ensures that any operations that alter the mutable data - // portion of this EditFstImpl cause the data_ member to be copied when its - // reference count is greater than 1. Note that this method is distinct from - // MutableFst::Mutate, which gets invoked whenever one of the basic mutation - // methods defined in MutableFst is invoked, such as SetInputSymbols. - // The MutateCheck here in EditFstImpl is invoked whenever one of the - // mutating methods specifically related to the types of edits provided - // by EditFst is performed, such as changing an arc of an existing state - // of the wrapped FST via a MutableArcIterator, or adding a new state via - // AddState(). - void MutateCheck() { - if (!data_.unique()) { - data_ = - std::make_shared>(*data_); - } - } - - // The FST that this FST wraps. The purpose of this class is to enable - // non-destructive edits on this wrapped FST. - std::unique_ptr wrapped_; - // The mutable data for this EditFst instance, with delegates for all the - // methods that can mutate data. - std::shared_ptr> data_; -}; - -template -inline void EditFstImpl::DeleteStates() { - data_->DeleteStates(); - // we are deleting all states, so just forget about pointer to wrapped_ - // and do what default constructor does: set wrapped_ to a new VectorFst - wrapped_ = std::make_unique(); - const auto new_props = - DeleteAllStatesProperties(FstImpl::Properties(), kStaticProperties); - FstImpl::SetProperties(new_props); -} - -template -EditFstImpl * -EditFstImpl::Read(std::istream &strm, - const FstReadOptions &opts) { - auto impl = std::make_unique(); - FstHeader hdr; - if (!impl->ReadHeader(strm, opts, kMinFileVersion, &hdr)) return nullptr; - impl->SetStart(hdr.Start()); - // Reads in wrapped FST. - FstReadOptions wrapped_opts(opts); - // Contained header was written out, so reads it in too. - wrapped_opts.header = nullptr; - std::unique_ptr> wrapped_fst(Fst::Read(strm, wrapped_opts)); - if (!wrapped_fst) return nullptr; - impl->wrapped_.reset(down_cast(wrapped_fst.release())); - impl->data_ = std::shared_ptr>( - EditFstData::Read(strm, opts)); - if (!impl->data_) return nullptr; - return impl.release(); -} - -} // namespace internal - -// Concrete, editable FST. This class attaches interface to implementation. -// -// EditFst is thread-compatible. -template , - typename MutableFstT = VectorFst> -class EditFst : public ImplToMutableFst< - internal::EditFstImpl> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using Impl = internal::EditFstImpl; - - friend class MutableArcIterator>; - - EditFst() : ImplToMutableFst(std::make_shared()) {} - - explicit EditFst(const Fst &fst) - : ImplToMutableFst(std::make_shared(fst)) {} - - explicit EditFst(const WrappedFstT &fst) - : ImplToMutableFst(std::make_shared(fst)) {} - - // See Fst<>::Copy() for doc. - EditFst(const EditFst &fst, bool safe = false) - : ImplToMutableFst(fst, safe) {} - - ~EditFst() override = default; - - // Gets a copy of this EditFst. See Fst<>::Copy() for further doc. - EditFst *Copy(bool safe = false) const override { - return new EditFst(*this, safe); - } - - EditFst &operator=(const EditFst &fst) { - SetImpl(fst.GetSharedImpl()); - return *this; - } - - EditFst &operator=(const Fst &fst) override { - SetImpl(std::make_shared(fst)); - return *this; - } - - // Reads an EditFst from an input stream, returning nullptr on error. - static EditFst *Read(std::istream &strm, const FstReadOptions &opts) { - auto *impl = Impl::Read(strm, opts); - return impl ? new EditFst(std::shared_ptr(impl)) : nullptr; - } - - // Reads an EditFst from a file, returning nullptr on error. If the source - // argument is an empty string, it reads from standard input. - static EditFst *Read(std::string_view source) { - auto *impl = ImplToExpandedFst>::Read(source); - return impl ? new EditFst(std::shared_ptr(impl)) : nullptr; - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const override { - return GetImpl()->Write(strm, opts); - } - - bool Write(const std::string &source) const override { - return Fst::WriteFile(source); - } - - void InitStateIterator(StateIteratorData *data) const override { - GetImpl()->InitStateIterator(data); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetImpl()->InitArcIterator(s, data); - } - - void InitMutableArcIterator(StateId s, - MutableArcIteratorData *data) override { - GetMutableImpl()->InitMutableArcIterator(s, data); - } - - private: - explicit EditFst(std::shared_ptr impl) : ImplToMutableFst(impl) {} - - using ImplToFst>::GetImpl; - using ImplToFst>::GetMutableImpl; - using ImplToFst>::SetImpl; -}; - -} // namespace fst - -#endif // FST_EDIT_FST_H_ diff --git a/contrib/fstlib/fst/encode.h b/contrib/fstlib/fst/encode.h deleted file mode 100644 index f5d2c2d..0000000 --- a/contrib/fstlib/fst/encode.h +++ /dev/null @@ -1,637 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to encode and decode an FST. - -#ifndef FST_ENCODE_H_ -#define FST_ENCODE_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -enum EncodeType { ENCODE = 1, DECODE = 2 }; - -inline constexpr uint8_t kEncodeLabels = 0x01; -inline constexpr uint8_t kEncodeWeights = 0x02; -inline constexpr uint8_t kEncodeFlags = 0x03; - -namespace internal { - -// Bits storing whether or not an encode table has input and/or output symbol -// tables, for internal use only. -inline constexpr uint8_t kEncodeHasISymbols = 0x04; -inline constexpr uint8_t kEncodeHasOSymbols = 0x08; - -// Identifies stream data as an encode table (and its endianity). -inline constexpr int32_t kEncodeMagicNumber = 2128178506; -// TODO(b/141172858): deprecated, remove by 2020-01-01. -inline constexpr int32_t kEncodeDeprecatedMagicNumber = 2129983209; - -} // namespace internal - -// Header for the encoder table. -class EncodeTableHeader { - public: - EncodeTableHeader() = default; - - // Getters. - - const std::string &ArcType() const { return arctype_; } - - uint8_t Flags() const { return flags_; } - - size_t Size() const { return size_; } - - // Setters. - - void SetArcType(std::string_view arctype) { - arctype_ = std::string(arctype); - } - - void SetFlags(uint8_t flags) { flags_ = flags; } - - void SetSize(size_t size) { size_ = size; } - - // IO. - - bool Read(std::istream &strm, std::string_view source); - - bool Write(std::ostream &strm, std::string_view source) const; - - private: - std::string arctype_; - uint8_t flags_; - size_t size_; -}; - -namespace internal { - -// The following class encapsulates implementation details for the encoding and -// decoding of label/weight triples used for encoding and decoding of FSTs. The -// EncodeTable is bidirectional, i.e, it stores both the Triple of encode labels -// and weights to a unique label, and the reverse. -template -class EncodeTable { - public: - using Label = typename Arc::Label; - using Weight = typename Arc::Weight; - - // Encoded data consists of arc input/output labels and arc weight. - struct Triple { - Triple() = default; - - Triple(Label ilabel, Label olabel, Weight weight) - : ilabel(ilabel), olabel(olabel), weight(std::move(weight)) {} - - // Constructs from arc and flags. - Triple(const Arc &arc, uint8_t flags) - : ilabel(arc.ilabel), - olabel(flags & kEncodeLabels ? arc.olabel : 0), - weight(flags & kEncodeWeights ? arc.weight : Weight::One()) {} - - static std::unique_ptr Read(std::istream &strm) { - auto triple = std::make_unique(); - ReadType(strm, &triple->ilabel); - ReadType(strm, &triple->olabel); - ReadType(strm, &triple->weight); - return triple; - } - - void Write(std::ostream &strm) const { - WriteType(strm, ilabel); - WriteType(strm, olabel); - WriteType(strm, weight); - } - - // Exploited below for TripleEqual functor. - bool operator==(const Triple &other) const { - return (ilabel == other.ilabel && olabel == other.olabel && - weight == other.weight); - } - - Label ilabel; - Label olabel; - Weight weight; - }; - - // Equality functor for two Triple pointers. - struct TripleEqual { - bool operator()(const Triple *x, const Triple *y) const { return *x == *y; } - }; - - // Hash functor for one Triple pointer. - class TripleHash { - public: - explicit TripleHash(uint8_t flags) : flags_(flags) {} - - size_t operator()(const Triple *triple) const { - size_t hash = triple->ilabel; - static constexpr int lshift = 5; - static constexpr int rshift = CHAR_BIT * sizeof(size_t) - 5; - if (flags_ & kEncodeLabels) { - hash = hash << lshift ^ hash >> rshift ^ triple->olabel; - } - if (flags_ & kEncodeWeights) { - hash = hash << lshift ^ hash >> rshift ^ triple->weight.Hash(); - } - return hash; - } - - private: - uint8_t flags_; - }; - - explicit EncodeTable(uint8_t flags) - : flags_(flags), triple2label_(1024, TripleHash(flags)) {} - - // Given an arc, encodes either input/output labels or input/costs or both. - Label Encode(const Arc &arc) { - // Encoding weights of a weighted superfinal transition could result in - // a clash with a true epsilon arc; to avoid this we hallucinate kNoLabel - // labels instead. - if (arc.nextstate == kNoStateId && (flags_ & kEncodeWeights)) { - return Encode(std::make_unique(kNoLabel, kNoLabel, arc.weight)); - } else { - return Encode(std::make_unique(arc, flags_)); - } - } - - // Given an encoded arc label, decodes back to input/output labels and costs. - const Triple *Decode(Label label) const { - if (label < 1 || label > triples_.size()) { - LOG(ERROR) << "EncodeTable::Decode: Unknown decode label: " << label; - return nullptr; - } - return triples_[label - 1].get(); - } - - size_t Size() const { return triples_.size(); } - - static EncodeTable *Read(std::istream &strm, std::string_view source); - - bool Write(std::ostream &strm, std::string_view source) const; - - // This is masked to hide internal-only isymbol and osymbol bits. - - uint8_t Flags() const { return flags_ & kEncodeFlags; } - - const SymbolTable *InputSymbols() const { return isymbols_.get(); } - - const SymbolTable *OutputSymbols() const { return osymbols_.get(); } - - void SetInputSymbols(const SymbolTable *syms) { - if (syms) { - isymbols_.reset(syms->Copy()); - flags_ |= kEncodeHasISymbols; - } else { - isymbols_.reset(); - flags_ &= ~kEncodeHasISymbols; - } - } - - void SetOutputSymbols(const SymbolTable *syms) { - if (syms) { - osymbols_.reset(syms->Copy()); - flags_ |= kEncodeHasOSymbols; - } else { - osymbols_.reset(); - flags_ &= ~kEncodeHasOSymbols; - } - } - - private: - Label Encode(std::unique_ptr triple) { - auto insert_result = - triple2label_.emplace(triple.get(), triples_.size() + 1); - if (insert_result.second) triples_.push_back(std::move(triple)); - return insert_result.first->second; - } - - uint8_t flags_; - std::vector> triples_; - std::unordered_map - triple2label_; - std::unique_ptr isymbols_; - std::unique_ptr osymbols_; - - EncodeTable(const EncodeTable &) = delete; - EncodeTable &operator=(const EncodeTable &) = delete; -}; - -template -EncodeTable *EncodeTable::Read(std::istream &strm, - std::string_view source) { - EncodeTableHeader hdr; - if (!hdr.Read(strm, source)) return nullptr; - const auto flags = hdr.Flags(); - const auto size = hdr.Size(); - auto table = std::make_unique(flags); - for (int64_t i = 0; i < size; ++i) { - table->triples_.emplace_back(std::move(Triple::Read(strm))); - table->triple2label_[table->triples_.back().get()] = table->triples_.size(); - } - if (flags & kEncodeHasISymbols) { - table->isymbols_.reset(SymbolTable::Read(strm, source)); - } - if (flags & kEncodeHasOSymbols) { - table->osymbols_.reset(SymbolTable::Read(strm, source)); - } - if (!strm) { - LOG(ERROR) << "EncodeTable::Read: Read failed: " << source; - return nullptr; - } - return table.release(); -} - -template -bool EncodeTable::Write(std::ostream &strm, - std::string_view source) const { - EncodeTableHeader hdr; - hdr.SetArcType(Arc::Type()); - hdr.SetFlags(flags_); // Real flags, not masked ones. - hdr.SetSize(Size()); - if (!hdr.Write(strm, source)) return false; - for (const auto &triple : triples_) triple->Write(strm); - if (flags_ & kEncodeHasISymbols) isymbols_->Write(strm); - if (flags_ & kEncodeHasOSymbols) osymbols_->Write(strm); - strm.flush(); - if (!strm) { - LOG(ERROR) << "EncodeTable::Write: Write failed: " << source; - return false; - } - return true; -} - -} // namespace internal - -// A mapper to encode/decode weighted transducers. Encoding of an FST is used -// for performing classical determinization or minimization on a weighted -// transducer viewing it as an unweighted acceptor over encoded labels. -// -// The mapper stores the encoding in a local hash table (EncodeTable). This -// table is shared (and reference-counted) between the encoder and decoder. -// A decoder has read-only access to the EncodeTable. -// -// The EncodeMapper allows on the fly encoding of the machine. As the -// EncodeTable is generated the same table may by used to decode the machine -// on the fly. For example in the following sequence of operations -// -// Encode -> Determinize -> Decode -// -// we will use the encoding table generated during the encode step in the -// decode, even though the encoding is not complete. -template -class EncodeMapper { - using Label = typename Arc::Label; - using Weight = typename Arc::Weight; - - public: - explicit EncodeMapper(uint8_t flags, EncodeType type = ENCODE) - : flags_(flags), - type_(type), - table_(std::make_shared>(flags)), - error_(false) {} - - EncodeMapper(const EncodeMapper &mapper) - : flags_(mapper.flags_), - type_(mapper.type_), - table_(mapper.table_), - error_(false) {} - - // Copy constructor but setting the type, typically to DECODE. - EncodeMapper(const EncodeMapper &mapper, EncodeType type) - : flags_(mapper.flags_), - type_(type), - table_(mapper.table_), - error_(mapper.error_) {} - - Arc operator()(const Arc &arc); - - MapFinalAction FinalAction() const { - return (type_ == ENCODE && (flags_ & kEncodeWeights)) - ? MAP_REQUIRE_SUPERFINAL - : MAP_NO_SUPERFINAL; - } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - uint8_t Flags() const { return flags_; } - - uint64_t Properties(uint64_t inprops) { - uint64_t outprops = inprops; - if (error_) outprops |= kError; - uint64_t mask = kFstProperties; - if (flags_ & kEncodeLabels) { - mask &= kILabelInvariantProperties & kOLabelInvariantProperties; - } - if (flags_ & kEncodeWeights) { - mask &= kILabelInvariantProperties & kWeightInvariantProperties & - (type_ == ENCODE ? kAddSuperFinalProperties - : kRmSuperFinalProperties); - } - if (type_ == ENCODE) mask |= kIDeterministic; - outprops &= mask; - if (type_ == ENCODE) { - if (flags_ & kEncodeLabels) { - outprops |= kAcceptor; - } - if (flags_ & kEncodeWeights) { - outprops |= kUnweighted | kUnweightedCycles; - } - } - return outprops; - } - - EncodeType Type() const { return type_; } - - static EncodeMapper *Read(std::istream &strm, std::string_view source, - EncodeType type = ENCODE) { - auto *table = internal::EncodeTable::Read(strm, source); - return table ? new EncodeMapper(table->Flags(), type, table) : nullptr; - } - - static EncodeMapper *Read(std::string_view source, - EncodeType type = ENCODE) { - std::ifstream strm(std::string(source), - std::ios_base::in | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "EncodeMapper: Can't open file: " << source; - return nullptr; - } - return Read(strm, source, type); - } - - bool Write(std::ostream &strm, std::string_view source) const { - return table_->Write(strm, source); - } - - bool Write(std::string_view source) const { - std::ofstream strm(std::string(source), - std::ios_base::out | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "EncodeMapper: Can't open file: " << source; - return false; - } - return Write(strm, source); - } - - const SymbolTable *InputSymbols() const { return table_->InputSymbols(); } - - const SymbolTable *OutputSymbols() const { return table_->OutputSymbols(); } - - void SetInputSymbols(const SymbolTable *syms) { - table_->SetInputSymbols(syms); - } - - void SetOutputSymbols(const SymbolTable *syms) { - table_->SetOutputSymbols(syms); - } - - private: - uint8_t flags_; - EncodeType type_; - std::shared_ptr> table_; - bool error_; - - explicit EncodeMapper(uint8_t flags, EncodeType type, - internal::EncodeTable *table) - : flags_(flags), type_(type), table_(table), error_(false) {} - - EncodeMapper &operator=(const EncodeMapper &) = delete; -}; - -template -Arc EncodeMapper::operator()(const Arc &arc) { - if (type_ == ENCODE) { - // If this arc is a hallucinated final state, and we're either not encoding - // weights, or we're encoding weights but this is non-final, we use an - // identity-encoding. - if (arc.nextstate == kNoStateId && - ((!(flags_ & kEncodeWeights) || - ((flags_ & kEncodeWeights) && arc.weight == Weight::Zero())))) { - return arc; - } else { - const auto label = table_->Encode(arc); - return Arc(label, flags_ & kEncodeLabels ? label : arc.olabel, - flags_ & kEncodeWeights ? Weight::One() : arc.weight, - arc.nextstate); - } - } else { // type_ == DECODE - if (arc.nextstate == kNoStateId) { - return arc; - } else { - if (arc.ilabel == 0) return arc; - if (flags_ & kEncodeLabels && arc.ilabel != arc.olabel) { - FSTERROR() << "EncodeMapper: Label-encoded arc has different " - "input and output labels"; - error_ = true; - } - if (flags_ & kEncodeWeights && arc.weight != Weight::One()) { - FSTERROR() << "EncodeMapper: Weight-encoded arc has non-trivial weight"; - error_ = true; - } - const auto triple = table_->Decode(arc.ilabel); - if (!triple) { - FSTERROR() << "EncodeMapper: Decode failed"; - error_ = true; - return Arc(kNoLabel, kNoLabel, Weight::NoWeight(), arc.nextstate); - } else if (triple->ilabel == kNoLabel) { - // Hallucinated kNoLabel from a weighted superfinal transition. - return Arc(0, 0, triple->weight, arc.nextstate); - } else { - return Arc(triple->ilabel, - flags_ & kEncodeLabels ? triple->olabel : arc.olabel, - flags_ & kEncodeWeights ? triple->weight : arc.weight, - arc.nextstate); - } - } - } -} - -// Complexity: O(E + V). -template -inline void Encode(MutableFst *fst, EncodeMapper *mapper) { - mapper->SetInputSymbols(fst->InputSymbols()); - mapper->SetOutputSymbols(fst->OutputSymbols()); - ArcMap(fst, mapper); -} - -template -inline void Decode(MutableFst *fst, const EncodeMapper &mapper) { - ArcMap(fst, EncodeMapper(mapper, DECODE)); - RmFinalEpsilon(fst); - fst->SetInputSymbols(mapper.InputSymbols()); - fst->SetOutputSymbols(mapper.OutputSymbols()); -} - -// On-the-fly encoding of an input FST. -// -// Complexity: -// -// Construction: O(1) -// Traversal: O(e + v) -// -// where e is the number of arcs visited and v is the number of states visited. -// Constant time and space to visit an input state or arc is assumed and -// exclusive of caching. -template -class EncodeFst : public ArcMapFst> { - public: - using Mapper = EncodeMapper; - using Impl = internal::ArcMapFstImpl; - - EncodeFst(const Fst &fst, Mapper *encoder) - : ArcMapFst(fst, encoder, ArcMapFstOptions()) { - encoder->SetInputSymbols(fst.InputSymbols()); - encoder->SetOutputSymbols(fst.OutputSymbols()); - } - - EncodeFst(const Fst &fst, const Mapper &encoder) - : ArcMapFst(fst, encoder, ArcMapFstOptions()) {} - - // See Fst<>::Copy() for doc. - EncodeFst(const EncodeFst &fst, bool copy = false) - : ArcMapFst(fst, copy) {} - - // Makes a copy of this EncodeFst. See Fst<>::Copy() for further doc. - EncodeFst *Copy(bool safe = false) const override { - if (safe) { - FSTERROR() << "EncodeFst::Copy(true): Not allowed"; - GetImpl()->SetProperties(kError, kError); - } - return new EncodeFst(*this); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; -}; - -// On-the-fly decoding of an input FST. -// -// Complexity: -// -// Construction: O(1). -// Traversal: O(e + v) -// -// Constant time and space to visit an input state or arc is assumed and -// exclusive of caching. -template -class DecodeFst : public ArcMapFst> { - public: - using Mapper = EncodeMapper; - using Impl = internal::ArcMapFstImpl; - - DecodeFst(const Fst &fst, const Mapper &encoder) - : ArcMapFst(fst, Mapper(encoder, DECODE), - ArcMapFstOptions()) { - GetMutableImpl()->SetInputSymbols(encoder.InputSymbols()); - GetMutableImpl()->SetOutputSymbols(encoder.OutputSymbols()); - } - - // See Fst<>::Copy() for doc. - DecodeFst(const DecodeFst &fst, bool safe = false) - : ArcMapFst(fst, safe) {} - - // Makes a copy of this DecodeFst. See Fst<>::Copy() for further doc. - DecodeFst *Copy(bool safe = false) const override { - return new DecodeFst(*this, safe); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; -}; - -// Specialization for EncodeFst. -template -class StateIterator> - : public StateIterator>> { - public: - explicit StateIterator(const EncodeFst &fst) - : StateIterator>>(fst) {} -}; - -// Specialization for EncodeFst. -template -class ArcIterator> - : public ArcIterator>> { - public: - ArcIterator(const EncodeFst &fst, typename Arc::StateId s) - : ArcIterator>>(fst, s) {} -}; - -// Specialization for DecodeFst. -template -class StateIterator> - : public StateIterator>> { - public: - explicit StateIterator(const DecodeFst &fst) - : StateIterator>>(fst) {} -}; - -// Specialization for DecodeFst. -template -class ArcIterator> - : public ArcIterator>> { - public: - ArcIterator(const DecodeFst &fst, typename Arc::StateId s) - : ArcIterator>>(fst, s) {} -}; - -// Useful aliases when using StdArc. - -using StdEncodeFst = EncodeFst; - -using StdDecodeFst = DecodeFst; - -} // namespace fst - -#endif // FST_ENCODE_H_ diff --git a/contrib/fstlib/fst/epsnormalize.h b/contrib/fstlib/fst/epsnormalize.h deleted file mode 100644 index b42a24c..0000000 --- a/contrib/fstlib/fst/epsnormalize.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function that implements epsilon-normalization. - -#ifndef FST_EPSNORMALIZE_H_ -#define FST_EPSNORMALIZE_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -enum EpsNormalizeType { EPS_NORM_INPUT, EPS_NORM_OUTPUT }; - -// Returns an equivalent FST that is epsilon-normalized. An acceptor is -// epsilon-normalized if it is epsilon-removed. A transducer is input -// epsilon-normalized if additionally if on each path any epsilon input -// label follows all non-epsilon input labels. Output epsilon-normalized -// is defined similarly. -// -// For more information, see: -// -// Mohri, M. 2002. Generic epsilon-removal and input epsilon-normalization -// algorithms for weighted transducers. International Journal of Computer -// Science, 13(1): 129-143, 2002. -template -void EpsNormalize(const Fst &ifst, MutableFst *ofst, - EpsNormalizeType type = EPS_NORM_INPUT) { - EpsNormalize(ifst, ofst, type); -} - -// Same as above, except allows specifying explicitly the gallic weight type. -template -void EpsNormalize(const Fst &ifst, MutableFst *ofst, - EpsNormalizeType type) { - VectorFst> gfst; - std::unique_ptr symbols; - if (type == EPS_NORM_INPUT) { - ArcMap(ifst, &gfst, ToGallicMapper()); - if (ifst.OutputSymbols()) symbols.reset(ifst.OutputSymbols()->Copy()); - } else { // type == EPS_NORM_OUTPUT - ArcMap(InvertFst(ifst), &gfst, ToGallicMapper()); - if (ifst.InputSymbols()) symbols.reset(ifst.InputSymbols()->Copy()); - } - RmEpsilon(&gfst); - FactorWeightFst, - GallicFactor> - fwfst(gfst); - ArcMap(fwfst, ofst, FromGallicMapper()); - ofst->SetOutputSymbols(symbols.get()); - if (type == EPS_NORM_OUTPUT) Invert(ofst); -} - -} // namespace fst - -#endif // FST_EPSNORMALIZE_H_ diff --git a/contrib/fstlib/fst/equal.h b/contrib/fstlib/fst/equal.h deleted file mode 100644 index cf4e51d..0000000 --- a/contrib/fstlib/fst/equal.h +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function to test equality of two FSTs. - -#ifndef FST_EQUAL_H_ -#define FST_EQUAL_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace fst { - -inline constexpr uint8_t kEqualFsts = 0x01; -inline constexpr uint8_t kEqualFstTypes = 0x02; -inline constexpr uint8_t kEqualCompatProperties = 0x04; -inline constexpr uint8_t kEqualCompatSymbols = 0x08; -inline constexpr uint8_t kEqualAll = - kEqualFsts | kEqualFstTypes | kEqualCompatProperties | kEqualCompatSymbols; - -class WeightApproxEqual { - public: - explicit WeightApproxEqual(float delta) : delta_(delta) {} - - // We use two weight types to avoid some conflicts caused by - // conversions. - template - bool operator()(const Weight1 &w1, const Weight2 &w2) const { - return ApproxEqual(w1, w2, delta_); - } - - private: - const float delta_; -}; - -// Tests if two FSTs have the same states and arcs in the same order (when -// etype & kEqualFst); optionally, also checks equality of FST types -// (etype & kEqualFstTypes) and compatibility of stored properties -// (etype & kEqualCompatProperties) and of symbol tables -// (etype & kEqualCompatSymbols). -template -bool Equal(const Fst &fst1, const Fst &fst2, WeightEqual weight_equal, - uint8_t etype = kEqualFsts) { - if ((etype & kEqualFstTypes) && (fst1.Type() != fst2.Type())) { - VLOG(1) << "Equal: Mismatched FST types (" << fst1.Type() - << " != " << fst2.Type() << ")"; - return false; - } - if ((etype & kEqualCompatProperties) && - !internal::CompatProperties(fst1.Properties(kCopyProperties, false), - fst2.Properties(kCopyProperties, false))) { - VLOG(1) << "Equal: Properties not compatible"; - return false; - } - if (etype & kEqualCompatSymbols) { - if (!CompatSymbols(fst1.InputSymbols(), fst2.InputSymbols(), false)) { - VLOG(1) << "Equal: Input symbols not compatible"; - return false; - } - if (!CompatSymbols(fst1.OutputSymbols(), fst2.OutputSymbols(), false)) { - VLOG(1) << "Equal: Output symbols not compatible"; - return false; - } - } - if (!(etype & kEqualFsts)) return true; - if (fst1.Start() != fst2.Start()) { - VLOG(1) << "Equal: Mismatched start states (" << fst1.Start() - << " != " << fst2.Start() << ")"; - return false; - } - StateIterator> siter1(fst1); - StateIterator> siter2(fst2); - while (!siter1.Done() || !siter2.Done()) { - if (siter1.Done() || siter2.Done()) { - VLOG(1) << "Equal: Mismatched number of states"; - return false; - } - const auto s1 = siter1.Value(); - const auto s2 = siter2.Value(); - if (s1 != s2) { - VLOG(1) << "Equal: Mismatched states (" << s1 << "!= " << s2 << ")"; - return false; - } - const auto &final1 = fst1.Final(s1); - const auto &final2 = fst2.Final(s2); - if (!weight_equal(final1, final2)) { - VLOG(1) << "Equal: Mismatched final weights at state " << s1 << " (" - << final1 << " != " << final2 << ")"; - return false; - } - ArcIterator> aiter1(fst1, s1); - ArcIterator> aiter2(fst2, s2); - for (auto a = 0; !aiter1.Done() || !aiter2.Done(); ++a) { - if (aiter1.Done() || aiter2.Done()) { - VLOG(1) << "Equal: Mismatched number of arcs at state " << s1; - return false; - } - const auto &arc1 = aiter1.Value(); - const auto &arc2 = aiter2.Value(); - if (arc1.ilabel != arc2.ilabel) { - VLOG(1) << "Equal: Mismatched arc input labels at state " << s1 - << ", arc " << a << " (" << arc1.ilabel << " != " << arc2.ilabel - << ")"; - return false; - } else if (arc1.olabel != arc2.olabel) { - VLOG(1) << "Equal: Mismatched arc output labels at state " << s1 - << ", arc " << a << " (" << arc1.olabel << " != " << arc2.olabel - << ")"; - return false; - } else if (!weight_equal(arc1.weight, arc2.weight)) { - VLOG(1) << "Equal: Mismatched arc weights at state " << s1 << ", arc " - << a << " (" << arc1.weight << " != " << arc2.weight << ")"; - return false; - } else if (arc1.nextstate != arc2.nextstate) { - VLOG(1) << "Equal: Mismatched next state at state " << s1 << ", arc " - << a << " (" << arc1.nextstate << " != " << arc2.nextstate - << ")"; - return false; - } - aiter1.Next(); - aiter2.Next(); - } - // Sanity checks: should never fail. - if (fst1.NumArcs(s1) != fst2.NumArcs(s2)) { - FSTERROR() << "Equal: Inconsistent arc counts at state " << s1 << " (" - << fst1.NumArcs(s1) << " != " << fst2.NumArcs(s2) << ")"; - return false; - } - if (fst1.NumInputEpsilons(s1) != fst2.NumInputEpsilons(s2)) { - FSTERROR() << "Equal: Inconsistent input epsilon counts at state " << s1 - << " (" << fst1.NumInputEpsilons(s1) - << " != " << fst2.NumInputEpsilons(s2) << ")"; - return false; - } - if (fst1.NumOutputEpsilons(s1) != fst2.NumOutputEpsilons(s2)) { - FSTERROR() << "Equal: Inconsistent output epsilon counts at state " << s1 - << " (" << fst1.NumOutputEpsilons(s1) - << " != " << fst2.NumOutputEpsilons(s2) << ")"; - } - siter1.Next(); - siter2.Next(); - } - return true; -} - -template -bool Equal(const Fst &fst1, const Fst &fst2, float delta = kDelta, - uint8_t etype = kEqualFsts) { - return Equal(fst1, fst2, WeightApproxEqual(delta), etype); -} - -// Support double deltas without forcing all clients to cast to float. -// Without this overload, Equal will be chosen, -// since it is a better match than double -> float narrowing, but -// the instantiation will fail. -template -bool Equal(const Fst &fst1, const Fst &fst2, double delta, - uint8_t etype = kEqualFsts) { - return Equal(fst1, fst2, WeightApproxEqual(static_cast(delta)), etype); -} - -} // namespace fst - -#endif // FST_EQUAL_H_ diff --git a/contrib/fstlib/fst/equivalent.h b/contrib/fstlib/fst/equivalent.h deleted file mode 100644 index 72e80dd..0000000 --- a/contrib/fstlib/fst/equivalent.h +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to determine the equivalence of two FSTs. - -#ifndef FST_EQUIVALENT_H_ -#define FST_EQUIVALENT_H_ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { -namespace internal { - -// Traits-like struct holding utility functions/typedefs/constants for -// the equivalence algorithm. -// -// Encoding device: in order to make the statesets of the two acceptors -// disjoint, we map Arc::StateId on the type MappedId. The states of -// the first acceptor are mapped on odd numbers (s -> 2s + 1), and -// those of the second one on even numbers (s -> 2s + 2). The number 0 -// is reserved for an implicit (non-final) dead state (required for -// the correct treatment of non-coaccessible states; kNoStateId is mapped to -// kDeadState for both acceptors). The union-find algorithm operates on the -// mapped IDs. -template -struct EquivalenceUtil { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using MappedId = StateId; // ID for an equivalence class. - - // MappedId for an implicit dead state. - static constexpr MappedId kDeadState = 0; - - // MappedId for lookup failure. - static constexpr MappedId kInvalidId = -1; - - // Maps state ID to the representative of the corresponding - // equivalence class. The parameter 'which_fst' takes the values 1 - // and 2, identifying the input FST. - static MappedId MapState(StateId s, int32_t which_fst) { - return (kNoStateId == s) ? kDeadState - : (static_cast(s) << 1) + which_fst; - } - - // Maps set ID to State ID. - static StateId UnMapState(MappedId id) { - return static_cast((--id) >> 1); - } - - // Convenience function: checks if state with MappedId s is final in - // acceptor fa. - static bool IsFinal(const Fst &fa, MappedId s) { - return (kDeadState == s) ? false - : (fa.Final(UnMapState(s)) != Weight::Zero()); - } - // Convenience function: returns the representative of ID in sets, - // creating a new set if needed. - static MappedId FindSet(UnionFind *sets, MappedId id) { - const auto repr = sets->FindSet(id); - if (repr != kInvalidId) { - return repr; - } else { - sets->MakeSet(id); - return id; - } - } -}; - -} // namespace internal - -// Equivalence checking algorithm: determines if the two FSTs fst1 and fst2 -// are equivalent. The input FSTs must be deterministic input-side epsilon-free -// acceptors, unweighted or with weights over a left semiring. Two acceptors are -// considered equivalent if they accept exactly the same set of strings (with -// the same weights). -// -// The algorithm (cf. Aho, Hopcroft and Ullman, "The Design and Analysis of -// Computer Programs") successively constructs sets of states that can be -// reached by the same prefixes, starting with a set containing the start states -// of both acceptors. A disjoint tree forest (the union-find algorithm) is used -// to represent the sets of states. The algorithm returns false if one of the -// constructed sets contains both final and non-final states. Returns an -// optional error value (useful when FST_FLAGS_error_fatal = false). -// -// Complexity: -// -// Quasi-linear, i.e., O(n G(n)), where -// -// n = |S1| + |S2| is the number of states in both acceptors -// -// G(n) is a very slowly growing function that can be approximated -// by 4 by all practical purposes. -template -bool Equivalent(const Fst &fst1, const Fst &fst2, - float delta = kDelta, bool *error = nullptr) { - using Weight = typename Arc::Weight; - if (error) *error = false; - // Check that the symbol table are compatible. - if (!CompatSymbols(fst1.InputSymbols(), fst2.InputSymbols()) || - !CompatSymbols(fst1.OutputSymbols(), fst2.OutputSymbols())) { - FSTERROR() << "Equivalent: Input/output symbol tables of 1st argument " - << "do not match input/output symbol tables of 2nd argument"; - if (error) *error = true; - return false; - } - // Check properties first. - static constexpr auto props = kNoEpsilons | kIDeterministic | kAcceptor; - if (fst1.Properties(props, true) != props) { - FSTERROR() << "Equivalent: 1st argument not an" - << " epsilon-free deterministic acceptor"; - if (error) *error = true; - return false; - } - if (fst2.Properties(props, true) != props) { - FSTERROR() << "Equivalent: 2nd argument not an" - << " epsilon-free deterministic acceptor"; - if (error) *error = true; - return false; - } - if ((fst1.Properties(kUnweighted, true) != kUnweighted) || - (fst2.Properties(kUnweighted, true) != kUnweighted)) { - VectorFst efst1(fst1); - VectorFst efst2(fst2); - Push(&efst1, REWEIGHT_TO_INITIAL, delta); - Push(&efst2, REWEIGHT_TO_INITIAL, delta); - ArcMap(&efst1, QuantizeMapper(delta)); - ArcMap(&efst2, QuantizeMapper(delta)); - EncodeMapper mapper(kEncodeWeights | kEncodeLabels, ENCODE); - ArcMap(&efst1, &mapper); - ArcMap(&efst2, &mapper); - return Equivalent(efst1, efst2); - } - using Util = internal::EquivalenceUtil; - using MappedId = typename Util::MappedId; - enum { FST1 = 1, FST2 = 2 }; // Required by Util::MapState(...) - auto s1 = Util::MapState(fst1.Start(), FST1); - auto s2 = Util::MapState(fst2.Start(), FST2); - // The union-find structure. - UnionFind eq_classes(1000, Util::kInvalidId); - // Initializes the union-find structure. - eq_classes.MakeSet(s1); - eq_classes.MakeSet(s2); - // Data structure for the (partial) acceptor transition function of fst1 and - // fst2: input labels mapped to pairs of MappedIds representing destination - // states of the corresponding arcs in fst1 and fst2, respectively. - using Label2StatePairMap = - std::unordered_map>; - Label2StatePairMap arc_pairs; - // Pairs of MappedId's to be processed, organized in a queue. - std::queue> q; - bool ret = true; - // Returns early if the start states differ w.r.t. finality. - if (Util::IsFinal(fst1, s1) != Util::IsFinal(fst2, s2)) ret = false; - // Main loop: explores the two acceptors in a breadth-first manner, updating - // the equivalence relation on the statesets. Loop invariant: each block of - // the states contains either final states only or non-final states only. - for (q.emplace(s1, s2); ret && !q.empty(); q.pop()) { - s1 = q.front().first; - s2 = q.front().second; - // Representatives of the equivalence classes of s1/s2. - const auto rep1 = Util::FindSet(&eq_classes, s1); - const auto rep2 = Util::FindSet(&eq_classes, s2); - if (rep1 != rep2) { - eq_classes.Union(rep1, rep2); - arc_pairs.clear(); - // Copies outgoing arcs starting at s1 into the hash-table. - if (Util::kDeadState != s1) { - ArcIterator> arc_iter(fst1, Util::UnMapState(s1)); - for (; !arc_iter.Done(); arc_iter.Next()) { - const auto &arc = arc_iter.Value(); - // Zero-weight arcs are treated as if they did not exist. - if (arc.weight != Weight::Zero()) { - arc_pairs[arc.ilabel].first = Util::MapState(arc.nextstate, FST1); - } - } - } - // Copies outgoing arcs starting at s2 into the hashtable. - if (Util::kDeadState != s2) { - ArcIterator> arc_iter(fst2, Util::UnMapState(s2)); - for (; !arc_iter.Done(); arc_iter.Next()) { - const auto &arc = arc_iter.Value(); - // Zero-weight arcs are treated as if they did not exist. - if (arc.weight != Weight::Zero()) { - arc_pairs[arc.ilabel].second = Util::MapState(arc.nextstate, FST2); - } - } - } - // Iterates through the hashtable and process pairs of target states. - for (const auto &arc_iter : arc_pairs) { - const auto &pair = arc_iter.second; - if (Util::IsFinal(fst1, pair.first) != - Util::IsFinal(fst2, pair.second)) { - // Detected inconsistency: return false. - ret = false; - break; - } - q.push(pair); - } - } - } - if (fst1.Properties(kError, false) || fst2.Properties(kError, false)) { - if (error) *error = true; - return false; - } - return ret; -} - -} // namespace fst - -#endif // FST_EQUIVALENT_H_ diff --git a/contrib/fstlib/fst/error-weight.h b/contrib/fstlib/fst/error-weight.h deleted file mode 100644 index 14d3d18..0000000 --- a/contrib/fstlib/fst/error-weight.h +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -#ifndef FST_ERROR_WEIGHT_H_ -#define FST_ERROR_WEIGHT_H_ - -#include -#include -#include - -#include -#include - -namespace fst { - -// A Weight that can never be instantiated. This is not a semi-ring. -// It is used for the arc type of empty FAR files. -struct ErrorWeight { - using ReverseWeight = ErrorWeight; - - ErrorWeight() { FSTERROR() << "ErrorWeight::ErrorWeight called"; } - - uint64_t Hash() const { return 0; } - bool Member() const { return false; } - ErrorWeight Quantize(float = 0.0) const { return ErrorWeight(); } - ReverseWeight Reverse() const { return ErrorWeight(); } - void Write(std::ostream &) const { } - - static constexpr uint64_t Properties() { return 0; } - static ErrorWeight Zero() { return ErrorWeight(); } - static ErrorWeight One() { return ErrorWeight(); } - static ErrorWeight NoWeight() { return ErrorWeight(); } - - static const std::string &Type() { - static const auto *const type = new std::string("error"); - return *type; - } -}; - -inline bool operator==(const ErrorWeight &, const ErrorWeight &) { - return false; -} -inline bool operator!=(const ErrorWeight &, const ErrorWeight &) { - return false; -} - -inline bool ApproxEqual(const ErrorWeight &, const ErrorWeight &, float) { - return false; -} -inline ErrorWeight Plus(const ErrorWeight &, const ErrorWeight &) { - return ErrorWeight(); -} -inline ErrorWeight Times(const ErrorWeight &, const ErrorWeight &) { - return ErrorWeight(); -} -inline ErrorWeight Divide(const ErrorWeight &, const ErrorWeight &) { - return ErrorWeight(); -} - -inline std::ostream &operator<<(std::ostream &strm, const ErrorWeight &) { - return strm; -} - -} // namespace fst - -#endif // FST_ERROR_WEIGHT_H_ diff --git a/contrib/fstlib/fst/expanded-fst.h b/contrib/fstlib/fst/expanded-fst.h deleted file mode 100644 index 2674e66..0000000 --- a/contrib/fstlib/fst/expanded-fst.h +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Generic FST augmented with state count-interface class definition. - -#ifndef FST_EXPANDED_FST_H_ -#define FST_EXPANDED_FST_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// A generic FST plus state count. -template -class ExpandedFst : public Fst { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - virtual StateId NumStates() const = 0; // State count - - std::optional NumStatesIfKnown() const override { - return NumStates(); - } - - // Get a copy of this ExpandedFst. See Fst<>::Copy() for further doc. - ExpandedFst *Copy(bool safe = false) const override = 0; - - // Read an ExpandedFst from an input stream; return NULL on error. - static ExpandedFst *Read(std::istream &strm, const FstReadOptions &opts) { - FstReadOptions ropts(opts); - FstHeader hdr; - if (ropts.header) { - hdr = *opts.header; - } else { - if (!hdr.Read(strm, opts.source)) return nullptr; - ropts.header = &hdr; - } - if (!(hdr.Properties() & kExpanded)) { - LOG(ERROR) << "ExpandedFst::Read: Not an ExpandedFst: " << ropts.source; - return nullptr; - } - const auto reader = - FstRegister::GetRegister()->GetReader(hdr.FstType()); - if (!reader) { - LOG(ERROR) << "ExpandedFst::Read: Unknown FST type \"" << hdr.FstType() - << "\" (arc type = \"" << A::Type() << "\"): " << ropts.source; - return nullptr; - } - auto *fst = reader(strm, ropts); - if (!fst) return nullptr; - return down_cast(fst); - } - - // Read an ExpandedFst from a file; return NULL on error. - // Empty source reads from standard input. - static ExpandedFst *Read(std::string_view source) { - if (!source.empty()) { - std::ifstream strm(std::string(source), - std::ios_base::in | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "ExpandedFst::Read: Can't open file: " << source; - return nullptr; - } - return Read(strm, FstReadOptions(source)); - } else { - return Read(std::cin, FstReadOptions("standard input")); - } - } -}; - -namespace internal { - -// ExpandedFst case - abstract methods. -template -inline typename Arc::Weight Final(const ExpandedFst &fst, - typename Arc::StateId s) { - return fst.Final(s); -} - -template -inline ssize_t NumArcs(const ExpandedFst &fst, typename Arc::StateId s) { - return fst.NumArcs(s); -} - -template -inline ssize_t NumInputEpsilons(const ExpandedFst &fst, - typename Arc::StateId s) { - return fst.NumInputEpsilons(s); -} - -template -inline ssize_t NumOutputEpsilons(const ExpandedFst &fst, - typename Arc::StateId s) { - return fst.NumOutputEpsilons(s); -} - -} // namespace internal - -// A useful alias when using StdArc. -using StdExpandedFst = ExpandedFst; - -// This is a helper class template useful for attaching an ExpandedFst -// interface to its implementation, handling reference counting. It -// delegates to ImplToFst the handling of the Fst interface methods. -template > -class ImplToExpandedFst : public ImplToFst { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - StateId NumStates() const override { return GetImpl()->NumStates(); } - - protected: - using ImplToFst::GetImpl; - - explicit ImplToExpandedFst(std::shared_ptr impl) - : ImplToFst(impl) {} - - ImplToExpandedFst(const ImplToExpandedFst &fst, bool safe) - : ImplToFst(fst, safe) {} - - static Impl *Read(std::istream &strm, const FstReadOptions &opts) { - return Impl::Read(strm, opts); - } - - // Read FST implementation from a file; return NULL on error. - // Empty source reads from standard input. - static Impl *Read(std::string_view source) { - if (!source.empty()) { - std::ifstream strm(std::string(source), - std::ios_base::in | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "ExpandedFst::Read: Can't open file: " << source; - return nullptr; - } - return Impl::Read(strm, FstReadOptions(source)); - } else { - return Impl::Read(std::cin, FstReadOptions("standard input")); - } - } -}; - -// Function to return the number of states in an FST, counting them -// if necessary. -template -typename Arc::StateId CountStates(const Fst &fst) { - if (std::optional num_states = - fst.NumStatesIfKnown()) { - return *num_states; - } else { - typename Arc::StateId nstates = 0; - for (StateIterator> siter(fst); !siter.Done(); siter.Next()) { - ++nstates; - } - return nstates; - } -} - -// Function to return the number of states in a vector of FSTs, counting them if -// necessary. -template -typename Arc::StateId CountStates(const std::vector *> &fsts) { - typename Arc::StateId nstates = 0; - for (const auto *fst : fsts) nstates += CountStates(*fst); - return nstates; -} - -// Function to return the number of arcs in an FST. -template -size_t CountArcs(const F &fst) { - size_t narcs = 0; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - narcs += fst.NumArcs(siter.Value()); - } - return narcs; -} - -} // namespace fst - -#endif // FST_EXPANDED_FST_H_ diff --git a/contrib/fstlib/fst/expander-cache.h b/contrib/fstlib/fst/expander-cache.h deleted file mode 100644 index 1c1a80b..0000000 --- a/contrib/fstlib/fst/expander-cache.h +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Cache implementations for ExpanderFst. -// -// Expander caches must expose a State type and a FindOrExpand template method: -// -// class ExpanderCache { -// public: -// class State; -// -// template -// State* FindOrExpander(Expander& expander, StateId id) { -// if (id is found in cache) return cached_state; -// -// // Use the provided expander to create a new cached state and cache it. -// expander.Expand(id, &new_state); -// insert new_state into cache; -// return new_state; -// } -// }; -// -// Cache implementations must be copyable and assignable. It is up to the -// implementation whether this means it will discard the contents of the cache, -// copy all of the cache, share some of the cache etc. It is *REQUIRED* that the -// copy be "safe", the copy and the original must be usable from concurrent -// threads without accessing any internally shared state. - -#ifndef FST_EXPANDER_CACHE_H_ -#define FST_EXPANDER_CACHE_H_ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace fst { - -// Stateful allocators can't be used without careful handling in threaded -// contexts, so arbitrary stl allocators aren't supported here. -template -class SimpleVectorCacheState { - public: - using Arc = A; - using Weight = typename Arc::Weight; - using StateId = typename Arc::StateId; - - void Reset() { - final_weight_ = Weight::Zero(); - niepsilons_ = 0; - noepsilons_ = 0; - arcs_.clear(); - } - - Weight Final() const { return final_weight_; } - - size_t NumInputEpsilons() const { return niepsilons_; } - - size_t NumOutputEpsilons() const { return noepsilons_; } - - size_t NumArcs() const { return arcs_.size(); } - - const Arc &GetArc(size_t n) const { return arcs_[n]; } - - const Arc *Arcs() const { return arcs_.empty() ? nullptr : &arcs_[0]; } - - void SetFinal(Weight weight) { final_weight_ = weight; } - - void ReserveArcs(size_t n) { arcs_.reserve(n); } - - void AddArc(const Arc &arc) { - if (arc.ilabel == 0) ++niepsilons_; - if (arc.olabel == 0) ++noepsilons_; - arcs_.push_back(arc); - } - - void AddArc(Arc &&arc) { - if (arc.ilabel == 0) ++niepsilons_; - if (arc.olabel == 0) ++noepsilons_; - arcs_.push_back(std::move(arc)); - } - - int *MutableRefCount() const { return nullptr; } - - private: - Weight final_weight_ = Weight::Zero(); - size_t niepsilons_ = 0; // Number of input epsilons. - size_t noepsilons_ = 0; // Number of output epsilons. - std::vector arcs_; -}; - -template -class NoGcKeepOneExpanderCache { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - // Reference-counted state. - class State : public SimpleVectorCacheState { - public: - int *MutableRefCount() { return &ref_count_; } - - void Reset() { - SimpleVectorCacheState::Reset(); - ref_count_ = 0; - } - - private: - int ref_count_ = 0; - - friend class NoGcKeepOneExpanderCache; - }; - - NoGcKeepOneExpanderCache() : state_(new State) {} - - NoGcKeepOneExpanderCache(const NoGcKeepOneExpanderCache ©) - : state_(new State(*copy.state_)) {} - - template - State *FindOrExpand(Expander &expander, StateId state_id) { - if (state_id == state_id_) return state_.get(); - if (state_->ref_count_ > 0) cache_[state_id_] = std::move(state_); - state_id_ = state_id; - if (cache_.empty()) { - state_->Reset(); - expander.Expand(state_id_, state_.get()); - return state_.get(); - } - if (auto i = cache_.find(state_id_); i != cache_.end()) { - state_ = std::move(i->second); - } - if (state_ == nullptr) { - state_ = std::make_unique(); - expander.Expand(state_id_, state_.get()); - } - return state_.get(); - } - - StateId state_id_ = kNoStateId; - std::unique_ptr state_; - std::unordered_map> cache_; -}; - -template -class HashExpanderCache { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using State = SimpleVectorCacheState; - - HashExpanderCache(const HashExpanderCache ©) { *this = copy; } - - HashExpanderCache &operator=(const HashExpanderCache ©) { - for (const auto &[id, state] : copy.cache_) { - cache_[id] = std::make_unique(*state); - } - return *this; - } - - ~HashExpanderCache() = default; - - template - State *FindOrExpand(Expander &expander, StateId state_id) { - auto [it, inserted] = cache_.emplace(state_id, nullptr); - if (inserted) { - it->second = std::make_unique(); - expander.Expand(state_id, it->second.get()); - } - return it->second.get(); - } - - private: - std::unordered_map> cache_; -}; - -template -class VectorExpanderCache { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using State = SimpleVectorCacheState; - - VectorExpanderCache() : vec_(0, nullptr) {} - - VectorExpanderCache(const VectorExpanderCache ©) { *this = copy; } - - VectorExpanderCache &operator=(const VectorExpanderCache ©) { - vec_.resize(copy.vec_.size()); - for (StateId i = 0; i < copy.vec_.size(); ++i) { - const auto *state = copy.vec_[i]; - if (state != nullptr) { - states_.emplace_back(*state); - vec_[i] = &states_.back(); - } - } - return *this; - } - - template - State *FindOrExpand(Expander &expander, StateId state_id) { - if (state_id >= vec_.size()) vec_.resize(state_id + 1); - auto **slot = &vec_[state_id]; - if (*slot == nullptr) { - states_.emplace_back(); - *slot = &states_.back(); - expander.Expand(state_id, *slot); - } - return *slot; - } - - private: - std::deque states_; - std::vector vec_; -}; - -template -using DefaultExpanderCache = VectorExpanderCache; - -} // namespace fst -#endif // FST_EXPANDER_CACHE_H_ diff --git a/contrib/fstlib/fst/expectation-weight.h b/contrib/fstlib/fst/expectation-weight.h deleted file mode 100644 index 698bb83..0000000 --- a/contrib/fstlib/fst/expectation-weight.h +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Expectation semiring, as described in: -// -// Eisner, J. 2002. Parameter estimation for probabilistic finite-state -// transducers. In Proceedings of the 40th Annual Meeting of the -// Association for Computational Linguistics, pages 1-8. -// -// Multiplex semiring operations and identities: -// -// One: -// Zero: -// Plus: + = <(a1 + a2), (b1 + b2)> -// Times: + = <(a1 * a2), [(a1 * b2) + (a2 * b1)]> -// Division (see Divide() for proof): -// For a left-semiring: -// / = -// For a right-semiring: -// / = -// -// It is commonly used to store a probability, random variable pair so that -// the shortest distance gives the posterior probability and the associated -// expected value. - -#ifndef FST_EXPECTATION_WEIGHT_H_ -#define FST_EXPECTATION_WEIGHT_H_ - -#include -#include -#include - -#include -#include -#include - -namespace fst { - -// W1 is usually a probability weight like LogWeight. -// W2 is usually a random variable or vector (see SignedLogWeight or -// SparsePowerWeight). -// -// If W1 is distinct from W2, it is required that there is an external product -// between W1 and W2 (that is, both Times(W1, W2) -> W2 and Times(W2, W1) -> W2 -// must be defined) and if both semirings are commutative, or left or right -// semirings, then the result must have those properties. -template -class ExpectationWeight : public PairWeight { - public: - using PairWeight::Value1; - using PairWeight::Value2; - - using PairWeight::Reverse; - using PairWeight::Quantize; - using PairWeight::Member; - - using ReverseWeight = - ExpectationWeight; - - ExpectationWeight() : PairWeight(Zero()) {} - - explicit ExpectationWeight(const PairWeight &weight) - : PairWeight(weight) {} - - ExpectationWeight(const W1 &w1, const W2 &w2) : PairWeight(w1, w2) {} - - static const ExpectationWeight &Zero() { - static const ExpectationWeight zero(W1::Zero(), W2::Zero()); - return zero; - } - - static const ExpectationWeight &One() { - static const ExpectationWeight one(W1::One(), W2::Zero()); - return one; - } - - static const ExpectationWeight &NoWeight() { - static const ExpectationWeight no_weight(W1::NoWeight(), W2::NoWeight()); - return no_weight; - } - - static const std::string &Type() { - static const std::string *const type = - new std::string("expectation_" + W1::Type() + "_" + W2::Type()); - return *type; - } - - ExpectationWeight Quantize(float delta = kDelta) const { - return ExpectationWeight(PairWeight::Quantize(delta)); - } - - ReverseWeight Reverse() const { - return ReverseWeight(PairWeight::Reverse()); - } - - bool Member() const { return PairWeight::Member(); } - - static constexpr uint64_t Properties() { - return W1::Properties() & W2::Properties() & - (kLeftSemiring | kRightSemiring | kCommutative | kIdempotent); - } -}; - -template -inline ExpectationWeight Plus(const ExpectationWeight &w1, - const ExpectationWeight &w2) { - return ExpectationWeight(Plus(w1.Value1(), w2.Value1()), - Plus(w1.Value2(), w2.Value2())); -} - -template -inline ExpectationWeight Times(const ExpectationWeight &w1, - const ExpectationWeight &w2) { - return ExpectationWeight( - Times(w1.Value1(), w2.Value1()), - Plus(Times(w1.Value1(), w2.Value2()), Times(w1.Value2(), w2.Value1()))); -} - -// Requires -// * Divide(W1, W1) -> W1 -// * Divide(W2, W1) -> W2 -// * Times(W1, W2) -> W2 -// (already required by Times(ExpectationWeight, ExpectationWeight).) -// * Minus(W2, W2) -> W2 -// (not part of the Weight interface, so Divide will not compile if -// Minus is not defined). -template -inline ExpectationWeight Divide(const ExpectationWeight &w1, - const ExpectationWeight &w2, - DivideType typ) { - // No special cases are required for !w1.Member(), !w2.Member(), or - // w2 == Zero(), since Minus and Divide will already return NoWeight() - // in these cases. - - // For a right-semiring, by the definition of Divide, we are looking for - // z = x / y such that (x / y) * y = x. - // Let = x, = y, = z. - // * = . - // By the definition of Times: - // z1 * y1 = x1 and - // z1 * y2 + z2 * y1 = x2. - // So z1 = x1 / y1, and - // z2 * y2 = x2 - z1 * y2 - // z2 = (x2 - z1 * y2) / y2. - // The left-semiring case is symmetric. The commutative case allows - // additional simplification to - // z2 = z1 * (x2 / x1 - y2 / y1) if x1 != 0 - // z2 = x2 / y1 if x1 == 0, but this requires testing against 0 - // with ApproxEquals. We just use the right-semiring result in - // this case. - const auto w11 = w1.Value1(); - const auto w12 = w1.Value2(); - const auto w21 = w2.Value1(); - const auto w22 = w2.Value2(); - const W1 q1 = Divide(w11, w21, typ); - if (typ == DIVIDE_LEFT) { - const W2 q2 = Divide(Minus(w12, Times(w22, q1)), w21, typ); - return ExpectationWeight(q1, q2); - } else { - // Right or commutative semiring. - const W2 q2 = Divide(Minus(w12, Times(q1, w22)), w21, typ); - return ExpectationWeight(q1, q2); - } -} - -// Specialization for expectation weight. -template -class Adder> { - public: - using Weight = ExpectationWeight; - - Adder() = default; - - explicit Adder(Weight w) : adder1_(w.Value1()), adder2_(w.Value2()) {} - - Weight Add(const Weight &w) { - adder1_.Add(w.Value1()); - adder2_.Add(w.Value2()); - return Sum(); - } - - Weight Sum() const { return Weight(adder1_.Sum(), adder2_.Sum()); } - - void Reset(Weight w = Weight::Zero()) { - adder1_.Reset(w.Value1()); - adder2_.Reset(w.Value2()); - } - - private: - Adder adder1_; - Adder adder2_; -}; - -// This function object generates weights by calling the underlying generators -// for the template weight types, like all other pair weight types. This is -// intended primarily for testing. -template -class WeightGenerate> { - public: - using Weight = ExpectationWeight; - using Generate = WeightGenerate>; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true) - : generate_(seed, allow_zero) {} - - Weight operator()() const { return Weight(generate_()); } - - private: - const Generate generate_; -}; - -} // namespace fst - -#endif // FST_EXPECTATION_WEIGHT_H_ diff --git a/contrib/fstlib/fst/factor-weight.h b/contrib/fstlib/fst/factor-weight.h deleted file mode 100644 index d218088..0000000 --- a/contrib/fstlib/fst/factor-weight.h +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes to factor weights in an FST. - -#ifndef FST_FACTOR_WEIGHT_H_ -#define FST_FACTOR_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -inline constexpr uint8_t kFactorFinalWeights = 0x01; -inline constexpr uint8_t kFactorArcWeights = 0x02; - -template -struct FactorWeightOptions : CacheOptions { - using Label = typename Arc::Label; - - float delta; - uint8_t mode; // Factor arc weights and/or final weights. - Label final_ilabel; // Input label of arc when factoring final weights. - Label final_olabel; // Output label of arc when factoring final weights. - bool increment_final_ilabel; // When factoring final w' results in > 1 arcs - bool increment_final_olabel; // at state, increment labels to make distinct? - - explicit FactorWeightOptions(const CacheOptions &opts, float delta = kDelta, - uint8_t mode = kFactorArcWeights | - kFactorFinalWeights, - Label final_ilabel = 0, Label final_olabel = 0, - bool increment_final_ilabel = false, - bool increment_final_olabel = false) - : CacheOptions(opts), - delta(delta), - mode(mode), - final_ilabel(final_ilabel), - final_olabel(final_olabel), - increment_final_ilabel(increment_final_ilabel), - increment_final_olabel(increment_final_olabel) {} - - explicit FactorWeightOptions(float delta = kDelta, - uint8_t mode = kFactorArcWeights | - kFactorFinalWeights, - Label final_ilabel = 0, Label final_olabel = 0, - bool increment_final_ilabel = false, - bool increment_final_olabel = false) - : delta(delta), - mode(mode), - final_ilabel(final_ilabel), - final_olabel(final_olabel), - increment_final_ilabel(increment_final_ilabel), - increment_final_olabel(increment_final_olabel) {} -}; - -// A factor iterator takes as argument a weight w and returns a sequence of -// pairs of weights (xi, yi) such that the sum of the products xi times yi is -// equal to w. If w is fully factored, the iterator should return nothing. -// -// template -// class FactorIterator { -// public: -// explicit FactorIterator(W w); -// -// bool Done() const; -// -// void Next(); -// -// std::pair Value() const; -// -// void Reset(); -// } - -// Factors trivially. -template -class IdentityFactor { - public: - explicit IdentityFactor(const W &weight) {} - - bool Done() const { return true; } - - void Next() {} - - std::pair Value() const { return std::make_pair(W::One(), W::One()); } - - void Reset() {} -}; - -// Factor the Fst to unfold it as needed so that every two paths leading to the -// same state have the same weight. Requires applying only to arc weights -// (FactorWeightOptions::mode == kFactorArcWeights). -template -class OneFactor { - public: - explicit OneFactor(const W &w) : weight_(w), done_(w == W::One()) {} - - bool Done() const { return done_; } - - void Next() { done_ = true; } - - std::pair Value() const { return std::make_pair(W::One(), weight_); } - - void Reset() { done_ = weight_ == W::One(); } - - private: - W weight_; - bool done_; -}; - -// Factors a StringWeight w as 'ab' where 'a' is a label. -template -class StringFactor { - public: - explicit StringFactor(const StringWeight &weight) - : weight_(weight), done_(weight.Size() <= 1) {} - - bool Done() const { return done_; } - - void Next() { done_ = true; } - - std::pair, StringWeight> Value() const { - using Weight = StringWeight; - typename Weight::Iterator siter(weight_); - Weight w1(siter.Value()); - Weight w2; - for (siter.Next(); !siter.Done(); siter.Next()) w2.PushBack(siter.Value()); - return std::make_pair(w1, w2); - } - - void Reset() { done_ = weight_.Size() <= 1; } - - private: - const StringWeight weight_; - bool done_; -}; - -// Factor a GallicWeight using StringFactor. -template -class GallicFactor { - public: - using GW = GallicWeight; - - explicit GallicFactor(const GW &weight) - : weight_(weight), done_(weight.Value1().Size() <= 1) {} - - bool Done() const { return done_; } - - void Next() { done_ = true; } - - std::pair Value() const { - StringFactor siter(weight_.Value1()); - GW w1(siter.Value().first, weight_.Value2()); - GW w2(siter.Value().second, W::One()); - return std::make_pair(w1, w2); - } - - void Reset() { done_ = weight_.Value1().Size() <= 1; } - - private: - const GW weight_; - bool done_; -}; - -// Specialization for the (general) GALLIC type GallicWeight. -template -class GallicFactor { - public: - using GW = GallicWeight; - using GRW = GallicWeight; - - explicit GallicFactor(const GW &weight) - : iter_(weight), - done_(weight.Size() == 0 || - (weight.Size() == 1 && weight.Back().Value1().Size() <= 1)) {} - - bool Done() const { return done_ || iter_.Done(); } - - void Next() { iter_.Next(); } - - void Reset() { iter_.Reset(); } - - std::pair Value() const { - const auto weight = iter_.Value(); - StringFactor siter( - weight.Value1()); - GRW w1(siter.Value().first, weight.Value2()); - GRW w2(siter.Value().second, W::One()); - return std::make_pair(GW(w1), GW(w2)); - } - - private: - UnionWeightIterator> iter_; - bool done_; -}; - -namespace internal { - -// Implementation class for FactorWeight -template -class FactorWeightFstImpl : public CacheImpl { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheBaseImpl>::EmplaceArc; - using CacheBaseImpl>::HasArcs; - using CacheBaseImpl>::HasFinal; - using CacheBaseImpl>::HasStart; - using CacheBaseImpl>::SetArcs; - using CacheBaseImpl>::SetFinal; - using CacheBaseImpl>::SetStart; - - struct Element { - Element() = default; - - Element(StateId s, Weight weight_) : state(s), weight(std::move(weight_)) {} - - StateId state; // Input state ID. - Weight weight; // Residual weight. - }; - - FactorWeightFstImpl(const Fst &fst, const FactorWeightOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - delta_(opts.delta), - mode_(opts.mode), - final_ilabel_(opts.final_ilabel), - final_olabel_(opts.final_olabel), - increment_final_ilabel_(opts.increment_final_ilabel), - increment_final_olabel_(opts.increment_final_olabel) { - SetType("factor_weight"); - const auto props = fst.Properties(kFstProperties, false); - SetProperties(FactorWeightProperties(props), kCopyProperties); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - if (mode_ == 0) { - LOG(WARNING) << "FactorWeightFst: Factor mode is set to 0; " - << "factoring neither arc weights nor final weights"; - } - } - - FactorWeightFstImpl(const FactorWeightFstImpl &impl) - : CacheImpl(impl), - fst_(impl.fst_->Copy(true)), - delta_(impl.delta_), - mode_(impl.mode_), - final_ilabel_(impl.final_ilabel_), - final_olabel_(impl.final_olabel_), - increment_final_ilabel_(impl.increment_final_ilabel_), - increment_final_olabel_(impl.increment_final_olabel_) { - SetType("factor_weight"); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - StateId Start() { - if (!HasStart()) { - const auto s = fst_->Start(); - if (s == kNoStateId) return kNoStateId; - SetStart(FindState(Element(fst_->Start(), Weight::One()))); - } - return CacheImpl::Start(); - } - - Weight Final(StateId s) { - if (!HasFinal(s)) { - const auto &element = elements_[s]; - const auto weight = - element.state == kNoStateId - ? element.weight - : Times(element.weight, fst_->Final(element.state)); - FactorIterator siter(weight); - if (!(mode_ & kFactorFinalWeights) || siter.Done()) { - SetFinal(s, weight); - } else { - SetFinal(s, Weight::Zero()); - } - } - return CacheImpl::Final(s); - } - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && fst_->Properties(kError, false)) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - // Finds state corresponding to an element, creating new state if element not - // found. - StateId FindState(const Element &element) { - if (!(mode_ & kFactorArcWeights) && element.weight == Weight::One() && - element.state != kNoStateId) { - while (unfactored_.size() <= element.state) - unfactored_.push_back(kNoStateId); - if (unfactored_[element.state] == kNoStateId) { - unfactored_[element.state] = elements_.size(); - elements_.push_back(element); - } - return unfactored_[element.state]; - } else { - const auto insert_result = - element_map_.emplace(element, elements_.size()); - if (insert_result.second) { - elements_.push_back(element); - } - return insert_result.first->second; - } - } - - // Computes the outgoing transitions from a state, creating new destination - // states as needed. - void Expand(StateId s) { - const auto element = elements_[s]; - if (element.state != kNoStateId) { - for (ArcIterator> ait(*fst_, element.state); !ait.Done(); - ait.Next()) { - const auto &arc = ait.Value(); - auto weight = Times(element.weight, arc.weight); - FactorIterator fiter(weight); - if (!(mode_ & kFactorArcWeights) || fiter.Done()) { - const auto dest = FindState(Element(arc.nextstate, Weight::One())); - EmplaceArc(s, arc.ilabel, arc.olabel, std::move(weight), dest); - } else { - for (; !fiter.Done(); fiter.Next()) { - auto pair = fiter.Value(); - const auto dest = - FindState(Element(arc.nextstate, pair.second.Quantize(delta_))); - EmplaceArc(s, arc.ilabel, arc.olabel, std::move(pair.first), dest); - } - } - } - } - if ((mode_ & kFactorFinalWeights) && - ((element.state == kNoStateId) || - (fst_->Final(element.state) != Weight::Zero()))) { - const auto weight = - element.state == kNoStateId - ? element.weight - : Times(element.weight, fst_->Final(element.state)); - auto ilabel = final_ilabel_; - auto olabel = final_olabel_; - for (FactorIterator fiter(weight); !fiter.Done(); fiter.Next()) { - auto pair = fiter.Value(); - const auto dest = - FindState(Element(kNoStateId, pair.second.Quantize(delta_))); - EmplaceArc(s, ilabel, olabel, std::move(pair.first), dest); - if (increment_final_ilabel_) ++ilabel; - if (increment_final_olabel_) ++olabel; - } - } - SetArcs(s); - } - - private: - // Equality function for Elements, assume weights have been quantized. - class ElementEqual { - public: - bool operator()(const Element &x, const Element &y) const { - return x.state == y.state && x.weight == y.weight; - } - }; - - // Hash function for Elements to Fst states. - class ElementKey { - public: - size_t operator()(const Element &x) const { - static constexpr auto prime = 7853; - return static_cast(x.state * prime + x.weight.Hash()); - } - }; - - using ElementMap = - std::unordered_map; - - std::unique_ptr> fst_; - float delta_; - uint8_t mode_; // Factoring arc and/or final weights. - Label final_ilabel_; // ilabel of arc created when factoring final weights. - Label final_olabel_; // olabel of arc created when factoring final weights. - bool increment_final_ilabel_; // When factoring final weights results in - bool increment_final_olabel_; // mutiple arcs, increment labels? - std::vector elements_; // Mapping from FST state to Element. - ElementMap element_map_; // Mapping from Element to FST state. - // Mapping between old/new StateId for states that do not need to be factored - // when mode_ is 0 or kFactorFinalWeights. - std::vector unfactored_; -}; - -} // namespace internal - -// FactorWeightFst takes as template parameter a FactorIterator as defined -// above. The result of weight factoring is a transducer equivalent to the -// input whose path weights have been factored according to the FactorIterator. -// States and transitions will be added as necessary. The algorithm is a -// generalization to arbitrary weights of the second step of the input -// epsilon-normalization algorithm. -// -// This class attaches interface to implementation and handles reference -// counting, delegating most methods to ImplToFst. -template -class FactorWeightFst - : public ImplToFst> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - using Impl = internal::FactorWeightFstImpl; - - friend class ArcIterator>; - friend class StateIterator>; - - explicit FactorWeightFst(const Fst &fst) - : ImplToFst( - std::make_shared(fst, FactorWeightOptions())) {} - - FactorWeightFst(const Fst &fst, const FactorWeightOptions &opts) - : ImplToFst(std::make_shared(fst, opts)) {} - - // See Fst<>::Copy() for doc. - FactorWeightFst(const FactorWeightFst &fst, bool copy) - : ImplToFst(fst, copy) {} - - // Get a copy of this FactorWeightFst. See Fst<>::Copy() for further doc. - FactorWeightFst *Copy(bool copy = false) const override { - return new FactorWeightFst(*this, copy); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - FactorWeightFst &operator=(const FactorWeightFst &) = delete; -}; - -// Specialization for FactorWeightFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const FactorWeightFst &fst) - : CacheStateIterator>( - fst, fst.GetMutableImpl()) {} -}; - -// Specialization for FactorWeightFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const FactorWeightFst &fst, StateId s) - : CacheArcIterator>( - fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void FactorWeightFst::InitStateIterator( - StateIteratorData *data) const { - data->base = - std::make_unique>>( - *this); -} - -} // namespace fst - -#endif // FST_FACTOR_WEIGHT_H_ diff --git a/contrib/fstlib/fst/filter-state.h b/contrib/fstlib/fst/filter-state.h deleted file mode 100644 index d464ec1..0000000 --- a/contrib/fstlib/fst/filter-state.h +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes for storing filter state in various algorithms like composition. - -#ifndef FST_FILTER_STATE_H_ -#define FST_FILTER_STATE_H_ - -#include -#include -#include -#include - -#include // For optional argument declarations -#include -#include - -namespace fst { - -// The filter state interface represents the state of a (e.g., composition) -// filter. -// -// class FilterState { -// public: -// // Required constructors. -// -// FilterState(); -// -// FilterState(const FilterState &fs); -// -// // An invalid filter state. -// static const FilterState NoState(); -// -// // Maps state to integer for hashing. -// size_t Hash() const; -// -// // Equality of filter states. -// bool operator==(const FilterState &fs) const; -// -// // Inequality of filter states. -// bool operator!=(const FilterState &fs) const; -// -// // Assignment to filter states. -// FilterState &operator=(const FilterState& fs); -// }; - -// Filter state that is a signed integral type. -template -class IntegerFilterState { - public: - IntegerFilterState() : state_(kNoStateId) {} - - explicit IntegerFilterState(T s) : state_(s) {} - - static const IntegerFilterState NoState() { return IntegerFilterState(); } - - size_t Hash() const { return static_cast(state_); } - - bool operator==(const IntegerFilterState &fs) const { - return state_ == fs.state_; - } - - bool operator!=(const IntegerFilterState &fs) const { - return state_ != fs.state_; - } - - T GetState() const { return state_; } - - private: - T state_; -}; - -using CharFilterState = IntegerFilterState; -using ShortFilterState = IntegerFilterState; // NOLINT -using IntFilterState = IntegerFilterState; - -// Filter state that is a weight (class). -template -class WeightFilterState { - public: - WeightFilterState() : weight_(W::Zero()) {} - - explicit WeightFilterState(W weight) : weight_(std::move(weight)) {} - - static const WeightFilterState NoState() { return WeightFilterState(); } - - size_t Hash() const { return weight_.Hash(); } - - bool operator==(const WeightFilterState &fs) const { - return weight_ == fs.weight_; - } - - bool operator!=(const WeightFilterState &fs) const { - return weight_ != fs.weight_; - } - - W GetWeight() const { return weight_; } - - private: - W weight_; -}; - -// Filter state is a list of signed integer types T. Order matters -// for equality. -template -class ListFilterState { - public: - ListFilterState() = default; - - explicit ListFilterState(T s) { list_.push_front(s); } - - static const ListFilterState NoState() { return ListFilterState(kNoStateId); } - - size_t Hash() const { - size_t h = 0; - for (const auto &elem : list_) h ^= h << 1 ^ elem; - return h; - } - - bool operator==(const ListFilterState &fs) const { return list_ == fs.list_; } - - bool operator!=(const ListFilterState &fs) const { return list_ != fs.list_; } - - const std::forward_list &GetState() const { return list_; } - - std::forward_list *GetMutableState() { return &list_; } - - private: - std::forward_list list_; -}; - -// Filter state that is the combination of two filter states. -template -class PairFilterState { - public: - using FilterState1 = FS1; - using FilterState2 = FS2; - - PairFilterState() : fs1_(FS1::NoState()), fs2_(FS2::NoState()) {} - - PairFilterState(const FilterState1 &fs1, const FilterState2 &fs2) - : fs1_(fs1), fs2_(fs2) {} - - static const PairFilterState NoState() { return PairFilterState(); } - - size_t Hash() const { - const auto h1 = fs1_.Hash(); - static constexpr auto lshift = 5; - static constexpr auto rshift = CHAR_BIT * sizeof(size_t) - 5; - return h1 << lshift ^ h1 >> rshift ^ fs2_.Hash(); - } - - bool operator==(const PairFilterState &fs) const { - return fs1_ == fs.fs1_ && fs2_ == fs.fs2_; - } - - bool operator!=(const PairFilterState &fs) const { - return fs1_ != fs.fs1_ || fs2_ != fs.fs2_; - } - - const FilterState1 &GetState1() const { return fs1_; } - - const FilterState2 &GetState2() const { return fs2_; } - - private: - FilterState1 fs1_; - FilterState2 fs2_; -}; - -// Single non-blocking filter state. -class TrivialFilterState { - public: - explicit TrivialFilterState(bool state = false) : state_(state) {} - - static const TrivialFilterState NoState() { return TrivialFilterState(); } - - size_t Hash() const { return 0; } - - bool operator==(const TrivialFilterState &fs) const { - return state_ == fs.state_; - } - - bool operator!=(const TrivialFilterState &fs) const { - return state_ != fs.state_; - } - - private: - bool state_; -}; - -} // namespace fst - -#endif // FST_FILTER_STATE_H_ diff --git a/contrib/fstlib/fst/flags.h b/contrib/fstlib/fst/flags.h deleted file mode 100644 index 761ad35..0000000 --- a/contrib/fstlib/fst/flags.h +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Google-style flag handling declarations and inline definitions. - -#ifndef FST_FLAGS_H_ -#define FST_FLAGS_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -// FLAGS USAGE: -// -// Definition example: -// -// DEFINE_int32(length, 0, "length"); -// -// This defines variable FST_FLAGS_length, initialized to 0. -// -// Declaration example: -// -// DECLARE_int32(length); -// -// SET_FLAGS() can be used to set flags from the command line -// using, for example, '--length=2'. -// -// ShowUsage() can be used to print out command and flag usage. - -#define DECLARE_bool(name) extern bool FST_FLAGS_ ## name -#define DECLARE_string(name) extern std::string FST_FLAGS_##name -#define DECLARE_int32(name) extern int32_t FST_FLAGS_##name -#define DECLARE_int64(name) extern int64_t FST_FLAGS_##name -#define DECLARE_uint64(name) extern uint64_t FST_FLAGS_##name -#define DECLARE_double(name) extern double FST_FLAGS_ ## name - -template -struct FlagDescription { - FlagDescription(T *addr, std::string_view doc, std::string_view type, - std::string_view file, const T val) - : address(addr), - doc_string(doc), - type_name(type), - file_name(file), - default_value(val) {} - - T *address; - std::string_view doc_string; - std::string_view type_name; - std::string_view file_name; - const T default_value; -}; - -template -class FlagRegister { - public: - static FlagRegister *GetRegister() { - static auto reg = new FlagRegister; - return reg; - } - - const FlagDescription &GetFlagDescription(const std::string &name) const { - fst::MutexLock l(&flag_lock_); - auto it = flag_table_.find(name); - return it != flag_table_.end() ? it->second : 0; - } - - void SetDescription(const std::string &name, const FlagDescription &desc) { - fst::MutexLock l(&flag_lock_); - flag_table_.insert(std::make_pair(name, desc)); - } - - bool SetFlag(const std::string &val, bool *address) const { - if (val == "true" || val == "1" || val.empty()) { - *address = true; - return true; - } else if (val == "false" || val == "0") { - *address = false; - return true; - } else { - return false; - } - } - - bool SetFlag(const std::string &val, std::string *address) const { - *address = val; - return true; - } - - bool SetFlag(const std::string &val, int32_t *address) const { - char *p = nullptr; - *address = strtol(val.c_str(), &p, 0); - return !val.empty() && *p == '\0'; - } - - bool SetFlag(const std::string &val, int64_t *address) const { - char *p = nullptr; - *address = strtoll(val.c_str(), &p, 0); - return !val.empty() && *p == '\0'; - } - - bool SetFlag(const std::string &val, uint64_t *address) const { - char *p = nullptr; - *address = strtoull(val.c_str(), &p, 0); - return !val.empty() && *p == '\0'; - } - - bool SetFlag(const std::string &val, double *address) const { - char *p = nullptr; - *address = strtod(val.c_str(), &p); - return !val.empty() && *p == '\0'; - } - - bool SetFlag(const std::string &arg, const std::string &val) const { - for (const auto &kv : flag_table_) { - const auto &name = kv.first; - const FlagDescription &desc = kv.second; - if (arg == name) return SetFlag(val, desc.address); - } - return false; - } - - void GetUsage( - std::set> *usage_set) const { - for (auto it = flag_table_.begin(); it != flag_table_.end(); ++it) { - const auto &name = it->first; - const FlagDescription &desc = it->second; - std::string usage = " --" + name; - usage += ": type = "; - usage += desc.type_name; - usage += ", default = "; - usage += GetDefault(desc.default_value) + "\n "; - usage += desc.doc_string; - usage_set->insert(std::make_pair(std::string(desc.file_name), usage)); - } - } - - private: - std::string GetDefault(bool default_value) const { - return default_value ? "true" : "false"; - } - - std::string GetDefault(const std::string &default_value) const { - return "\"" + default_value + "\""; - } - - template - std::string GetDefault(const V &default_value) const { - std::ostringstream strm; - strm << default_value; - return strm.str(); - } - - mutable fst::Mutex flag_lock_; // Multithreading lock. - std::map> flag_table_; -}; - -template -class FlagRegisterer { - public: - FlagRegisterer(const std::string &name, const FlagDescription &desc) { - auto registr = FlagRegister::GetRegister(); - registr->SetDescription(name, desc); - } - - private: - FlagRegisterer(const FlagRegisterer &) = delete; - FlagRegisterer &operator=(const FlagRegisterer &) = delete; -}; - - -#define DEFINE_VAR(type, name, value, doc) \ - type FST_FLAGS_ ## name = value; \ - static FlagRegisterer \ - name ## _flags_registerer(#name, FlagDescription(&FST_FLAGS_ ## name, \ - doc, \ - #type, \ - __FILE__, \ - value)) - -#define DEFINE_bool(name, value, doc) DEFINE_VAR(bool, name, value, doc) -#define DEFINE_string(name, value, doc) \ - DEFINE_VAR(std::string, name, value, doc) -#define DEFINE_int32(name, value, doc) DEFINE_VAR(int32_t, name, value, doc) -#define DEFINE_int64(name, value, doc) DEFINE_VAR(int64_t, name, value, doc) -#define DEFINE_uint64(name, value, doc) DEFINE_VAR(uint64_t, name, value, doc) -#define DEFINE_double(name, value, doc) DEFINE_VAR(double, name, value, doc) - - -// Temporary directory. -DECLARE_string(tmpdir); - -void SetFlags(const char *usage, int *argc, char ***argv, bool remove_flags, - const char *src = ""); - -// This is an unpleasant hack around SetFlag API. -template -void SetFlag(Type *flag, Value value) { - *flag = Type(value); -} - -void FailedNewHandler(); - -#define SET_FLAGS(usage, argc, argv, rmflags) \ -std::set_new_handler(FailedNewHandler); \ -SetFlags(usage, argc, argv, rmflags, __FILE__) - -// Deprecated; for backward compatibility. -inline void InitFst(const char *usage, int *argc, char ***argv, bool rmflags) { - return SetFlags(usage, argc, argv, rmflags); -} - -void ShowUsage(bool long_usage = true); - -#endif // FST_FLAGS_H_ diff --git a/contrib/fstlib/fst/float-weight.h b/contrib/fstlib/fst/float-weight.h deleted file mode 100644 index 9de861d..0000000 --- a/contrib/fstlib/fst/float-weight.h +++ /dev/null @@ -1,1183 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Float weight set and associated semiring operation definitions. - -#ifndef FST_FLOAT_WEIGHT_H_ -#define FST_FLOAT_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -namespace internal { -// TODO(wolfsonkin): Replace with `std::isnan` if and when that ends up -// constexpr. For context, see -// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0533r6.pdf. -template -inline constexpr bool IsNan(T value) { - return value != value; -} -} // namespace internal - -// Numeric limits class. -template -class FloatLimits { - public: - static constexpr T PosInfinity() { - return std::numeric_limits::infinity(); - } - - static constexpr T NegInfinity() { return -PosInfinity(); } - - static constexpr T NumberBad() { return std::numeric_limits::quiet_NaN(); } -}; - -// Weight class to be templated on floating-points types. -template -class FloatWeightTpl { - public: - using ValueType = T; - - FloatWeightTpl() noexcept = default; - - constexpr FloatWeightTpl(T f) : value_(f) {} // NOLINT - - std::istream &Read(std::istream &strm) { return ReadType(strm, &value_); } - - std::ostream &Write(std::ostream &strm) const { - return WriteType(strm, value_); - } - - size_t Hash() const { - size_t hash = 0; - // Avoid using union, which would be undefined behavior. - // Use memcpy, similar to bit_cast, but sizes may be different. - // This should be optimized into a single move instruction by - // any reasonable compiler. - std::memcpy(&hash, &value_, std::min(sizeof(hash), sizeof(value_))); - return hash; - } - - constexpr const T &Value() const { return value_; } - - protected: - void SetValue(const T &f) { value_ = f; } - - static constexpr std::string_view GetPrecisionString() { - return sizeof(T) == 4 ? "" - : sizeof(T) == 1 ? "8" - : sizeof(T) == 2 ? "16" - : sizeof(T) == 8 ? "64" - : "unknown"; - } - - private: - T value_; -}; - -// Single-precision float weight. -using FloatWeight = FloatWeightTpl; - -template -constexpr bool operator==(const FloatWeightTpl &w1, - const FloatWeightTpl &w2) { -#if (defined(__i386__) || defined(__x86_64__)) && !defined(__SSE2_MATH__) -// With i387 instructions, excess precision on a weight in an 80-bit -// register may cause it to compare unequal to that same weight when -// stored to memory. This breaks =='s reflexivity, in turn breaking -// NaturalLess. -#error "Please compile with -msse -mfpmath=sse, or equivalent." -#endif - return w1.Value() == w2.Value(); -} - -// These seemingly unnecessary overloads are actually needed to make -// comparisons like FloatWeightTpl == float compile. If only the -// templated version exists, the FloatWeightTpl(float) conversion -// won't be found. -constexpr bool operator==(const FloatWeightTpl &w1, - const FloatWeightTpl &w2) { - return operator==(w1, w2); -} - -constexpr bool operator==(const FloatWeightTpl &w1, - const FloatWeightTpl &w2) { - return operator==(w1, w2); -} - -template -constexpr bool operator!=(const FloatWeightTpl &w1, - const FloatWeightTpl &w2) { - return !(w1 == w2); -} - -constexpr bool operator!=(const FloatWeightTpl &w1, - const FloatWeightTpl &w2) { - return operator!=(w1, w2); -} - -constexpr bool operator!=(const FloatWeightTpl &w1, - const FloatWeightTpl &w2) { - return operator!=(w1, w2); -} - -template -constexpr bool FloatApproxEqual(T w1, T w2, float delta = kDelta) { - return w1 <= w2 + delta && w2 <= w1 + delta; -} - -template -constexpr bool ApproxEqual(const FloatWeightTpl &w1, - const FloatWeightTpl &w2, float delta = kDelta) { - return FloatApproxEqual(w1.Value(), w2.Value(), delta); -} - -template -inline std::ostream &operator<<(std::ostream &strm, - const FloatWeightTpl &w) { - if (w.Value() == FloatLimits::PosInfinity()) { - return strm << "Infinity"; - } else if (w.Value() == FloatLimits::NegInfinity()) { - return strm << "-Infinity"; - } else if (internal::IsNan(w.Value())) { - return strm << "BadNumber"; - } else { - return strm << w.Value(); - } -} - -template -inline std::istream &operator>>(std::istream &strm, FloatWeightTpl &w) { - std::string s; - strm >> s; - if (s == "Infinity") { - w = FloatWeightTpl(FloatLimits::PosInfinity()); - } else if (s == "-Infinity") { - w = FloatWeightTpl(FloatLimits::NegInfinity()); - } else { - char *p; - T f = strtod(s.c_str(), &p); - if (p < s.c_str() + s.size()) { - strm.clear(std::ios::badbit); - } else { - w = FloatWeightTpl(f); - } - } - return strm; -} - -// Tropical semiring: (min, +, inf, 0). -template -class TropicalWeightTpl : public FloatWeightTpl { - public: - using typename FloatWeightTpl::ValueType; - using FloatWeightTpl::Value; - using ReverseWeight = TropicalWeightTpl; - using Limits = FloatLimits; - - TropicalWeightTpl() noexcept : FloatWeightTpl() {} - - constexpr TropicalWeightTpl(T f) : FloatWeightTpl(f) {} - - static constexpr TropicalWeightTpl Zero() { return Limits::PosInfinity(); } - - static constexpr TropicalWeightTpl One() { return 0; } - - static constexpr TropicalWeightTpl NoWeight() { - return Limits::NumberBad(); - } - - static const std::string &Type() { - static const std::string *const type = new std::string( - fst::StrCat("tropical", FloatWeightTpl::GetPrecisionString())); - return *type; - } - - constexpr bool Member() const { - // All floating point values except for NaNs and negative infinity are valid - // tropical weights. - // - // Testing membership of a given value can be done by simply checking that - // it is strictly greater than negative infinity, which fails for negative - // infinity itself but also for NaNs. This can usually be accomplished in a - // single instruction (such as *UCOMI* on x86) without branching logic. - // - // An additional wrinkle involves constexpr correctness of floating point - // comparisons against NaN. GCC is uneven when it comes to which expressions - // it considers compile-time constants. In particular, current versions of - // GCC do not always consider (nan < inf) to be a constant expression, but - // do consider (inf < nan) to be a constant expression. (See - // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88173 and - // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88683 for details.) In order - // to allow Member() to be a constexpr function accepted by GCC, we write - // the comparison here as (-inf < v). - return Limits::NegInfinity() < Value(); - } - - TropicalWeightTpl Quantize(float delta = kDelta) const { - if (!Member() || Value() == Limits::PosInfinity()) { - return *this; - } else { - return TropicalWeightTpl(std::floor(Value() / delta + 0.5F) * delta); - } - } - - constexpr TropicalWeightTpl Reverse() const { return *this; } - - static constexpr uint64_t Properties() { - return kLeftSemiring | kRightSemiring | kCommutative | kPath | kIdempotent; - } -}; - -// Single precision tropical weight. -using TropicalWeight = TropicalWeightTpl; - -template -constexpr TropicalWeightTpl Plus(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2) { - return (!w1.Member() || !w2.Member()) ? TropicalWeightTpl::NoWeight() - : w1.Value() < w2.Value() ? w1 - : w2; -} - -// See comment at operator==(FloatWeightTpl, FloatWeightTpl) -// for why these overloads are present. -constexpr TropicalWeightTpl Plus(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2) { - return Plus(w1, w2); -} - -constexpr TropicalWeightTpl Plus(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2) { - return Plus(w1, w2); -} - -template -constexpr TropicalWeightTpl Times(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2) { - // The following is safe in the context of the Tropical (and Log) semiring - // for all IEEE floating point values, including infinities and NaNs, - // because: - // - // * If one or both of the floating point Values is NaN and hence not a - // Member, the result of addition below is NaN, so the result is not a - // Member. This supersedes all other cases, so we only consider non-NaN - // values next. - // - // * If both Values are finite, there is no issue. - // - // * If one of the Values is infinite, or if both are infinities with the - // same sign, the result of floating point addition is the same infinity, - // so there is no issue. - // - // * If both of the Values are infinities with opposite signs, the result of - // adding IEEE floating point -inf + inf is NaN and hence not a Member. But - // since -inf was not a Member to begin with, returning a non-Member result - // is fine as well. - return TropicalWeightTpl(w1.Value() + w2.Value()); -} - -constexpr TropicalWeightTpl Times(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2) { - return Times(w1, w2); -} - -constexpr TropicalWeightTpl Times(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2) { - return Times(w1, w2); -} - -template -constexpr TropicalWeightTpl Divide(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - // The following is safe in the context of the Tropical (and Log) semiring - // for all IEEE floating point values, including infinities and NaNs, - // because: - // - // * If one or both of the floating point Values is NaN and hence not a - // Member, the result of subtraction below is NaN, so the result is not a - // Member. This supersedes all other cases, so we only consider non-NaN - // values next. - // - // * If both Values are finite, there is no issue. - // - // * If w2.Value() is -inf (and hence w2 is not a Member), the result of ?: - // below is NoWeight, which is not a Member. - // - // Whereas in IEEE floating point semantics 0/inf == 0, this does not carry - // over to this semiring (since TropicalWeight(-inf) would be the analogue - // of floating point inf) and instead Divide(Zero(), TropicalWeight(-inf)) - // is NoWeight(). - // - // * If w2.Value() is inf (and hence w2 is Zero), the resulting floating - // point value is either NaN (if w1 is Zero or if w1.Value() is NaN) and - // hence not a Member, or it is -inf and hence not a Member; either way, - // division by Zero results in a non-Member result. - using Weight = TropicalWeightTpl; - return w2.Member() ? Weight(w1.Value() - w2.Value()) : Weight::NoWeight(); -} - -constexpr TropicalWeightTpl Divide(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -constexpr TropicalWeightTpl Divide(const TropicalWeightTpl &w1, - const TropicalWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -// Power(w, n) calculates the n-th power of w with respect to semiring Times. -// -// In the case of the Tropical (and Log) semiring, the exponent n is not -// restricted to be an integer. It can be a floating point value, for example. -// -// In weight.h, a narrower and hence more broadly applicable version of -// Power(w, n) is defined for arbitrary weight types and non-negative integer -// exponents n (of type size_t) and implemented in terms of repeated -// multiplication using Times. -// -// Without further provisions this means that, when an expression such as -// -// Power(TropicalWeightTpl::One(), static_cast(2)) -// -// is specified, the overload of Power() is ambiguous. The template function -// below could be instantiated as -// -// Power(const TropicalWeightTpl &, size_t) -// -// and the template function defined in weight.h (further specialized below) -// could be instantiated as -// -// Power>(const TropicalWeightTpl &, size_t) -// -// That would lead to two definitions with identical signatures, which results -// in a compilation error. To avoid that, we hide the definition of Power -// when V is size_t, so only Power is visible. Power is further -// specialized to Power>, and the overloaded definition -// of Power is made conditionally available only to that template -// specialization. - -template , - typename std::enable_if_t * = nullptr> -constexpr TropicalWeightTpl Power(const TropicalWeightTpl &w, V n) { - using Weight = TropicalWeightTpl; - return (!w.Member() || internal::IsNan(n)) ? Weight::NoWeight() - : (n == 0 || w == Weight::One()) ? Weight::One() - : Weight(w.Value() * n); -} - -// Specializes the library-wide template to use the above implementation; rules -// of function template instantiation require this be a full instantiation. - -template <> -constexpr TropicalWeightTpl Power>( - const TropicalWeightTpl &weight, size_t n) { - return Power(weight, n); -} - -template <> -constexpr TropicalWeightTpl Power>( - const TropicalWeightTpl &weight, size_t n) { - return Power(weight, n); -} - -// Log semiring: (log(e^-x + e^-y), +, inf, 0). -template -class LogWeightTpl : public FloatWeightTpl { - public: - using typename FloatWeightTpl::ValueType; - using FloatWeightTpl::Value; - using ReverseWeight = LogWeightTpl; - using Limits = FloatLimits; - - LogWeightTpl() noexcept : FloatWeightTpl() {} - - constexpr LogWeightTpl(T f) : FloatWeightTpl(f) {} - - static constexpr LogWeightTpl Zero() { return Limits::PosInfinity(); } - - static constexpr LogWeightTpl One() { return 0; } - - static constexpr LogWeightTpl NoWeight() { return Limits::NumberBad(); } - - static const std::string &Type() { - static const std::string *const type = new std::string( - fst::StrCat("log", FloatWeightTpl::GetPrecisionString())); - return *type; - } - - constexpr bool Member() const { - // The comments for TropicalWeightTpl<>::Member() apply here unchanged. - return Limits::NegInfinity() < Value(); - } - - LogWeightTpl Quantize(float delta = kDelta) const { - if (!Member() || Value() == Limits::PosInfinity()) { - return *this; - } else { - return LogWeightTpl(std::floor(Value() / delta + 0.5F) * delta); - } - } - - constexpr LogWeightTpl Reverse() const { return *this; } - - static constexpr uint64_t Properties() { - return kLeftSemiring | kRightSemiring | kCommutative; - } -}; - -// Single-precision log weight. -using LogWeight = LogWeightTpl; - -// Double-precision log weight. -using Log64Weight = LogWeightTpl; - -namespace internal { - -// -log(e^-x + e^-y) = x - LogPosExp(y - x), assuming y >= x. -inline double LogPosExp(double x) { - DCHECK(!(x < 0)); // NB: NaN values are allowed. - return log1p(exp(-x)); -} - -// -log(e^-x - e^-y) = x - LogNegExp(y - x), assuming y >= x. -inline double LogNegExp(double x) { - DCHECK(!(x < 0)); // NB: NaN values are allowed. - return log1p(-exp(-x)); -} - -// a +_log b = -log(e^-a + e^-b) = KahanLogSum(a, b, ...). -// Kahan compensated summation provides an error bound that is -// independent of the number of addends. Assumes b >= a; -// c is the compensation. -inline double KahanLogSum(double a, double b, double *c) { - DCHECK_GE(b, a); - double y = -LogPosExp(b - a) - *c; - double t = a + y; - *c = (t - a) - y; - return t; -} - -// a -_log b = -log(e^-a - e^-b) = KahanLogDiff(a, b, ...). -// Kahan compensated summation provides an error bound that is -// independent of the number of addends. Assumes b > a; -// c is the compensation. -inline double KahanLogDiff(double a, double b, double *c) { - DCHECK_GT(b, a); - double y = -LogNegExp(b - a) - *c; - double t = a + y; - *c = (t - a) - y; - return t; -} - -} // namespace internal - -template -inline LogWeightTpl Plus(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - using Limits = FloatLimits; - const T f1 = w1.Value(); - const T f2 = w2.Value(); - if (f1 == Limits::PosInfinity()) { - return w2; - } else if (f2 == Limits::PosInfinity()) { - return w1; - } else if (f1 > f2) { - return LogWeightTpl(f2 - internal::LogPosExp(f1 - f2)); - } else { - return LogWeightTpl(f1 - internal::LogPosExp(f2 - f1)); - } -} - -inline LogWeightTpl Plus(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - return Plus(w1, w2); -} - -inline LogWeightTpl Plus(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - return Plus(w1, w2); -} - -// Returns NoWeight if w1 < w2 (w1.Value() > w2.Value()). -template -inline LogWeightTpl Minus(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - using Limits = FloatLimits; - const T f1 = w1.Value(); - const T f2 = w2.Value(); - if (f1 > f2) return LogWeightTpl::NoWeight(); - if (f2 == Limits::PosInfinity()) return f1; - const T d = f2 - f1; - if (d == Limits::PosInfinity()) return f1; - return f1 - internal::LogNegExp(d); -} - -inline LogWeightTpl Minus(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - return Minus(w1, w2); -} - -inline LogWeightTpl Minus(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - return Minus(w1, w2); -} - -template -constexpr LogWeightTpl Times(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - // The comments for Times(Tropical...) above apply here unchanged. - return LogWeightTpl(w1.Value() + w2.Value()); -} - -constexpr LogWeightTpl Times(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - return Times(w1, w2); -} - -constexpr LogWeightTpl Times(const LogWeightTpl &w1, - const LogWeightTpl &w2) { - return Times(w1, w2); -} - -template -constexpr LogWeightTpl Divide(const LogWeightTpl &w1, - const LogWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - // The comments for Divide(Tropical...) above apply here unchanged. - using Weight = LogWeightTpl; - return w2.Member() ? Weight(w1.Value() - w2.Value()) : Weight::NoWeight(); -} - -constexpr LogWeightTpl Divide(const LogWeightTpl &w1, - const LogWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -constexpr LogWeightTpl Divide(const LogWeightTpl &w1, - const LogWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -// The comments for Power<>(Tropical...) above apply here unchanged. - -template , - typename std::enable_if_t * = nullptr> -constexpr LogWeightTpl Power(const LogWeightTpl &w, V n) { - using Weight = LogWeightTpl; - return (!w.Member() || internal::IsNan(n)) ? Weight::NoWeight() - : (n == 0 || w == Weight::One()) ? Weight::One() - : Weight(w.Value() * n); -} - -// Specializes the library-wide template to use the above implementation; rules -// of function template instantiation require this be a full instantiation. - -template <> -constexpr LogWeightTpl Power>( - const LogWeightTpl &weight, size_t n) { - return Power(weight, n); -} - -template <> -constexpr LogWeightTpl Power>( - const LogWeightTpl &weight, size_t n) { - return Power(weight, n); -} - -// Specialization using the Kahan compensated summation. -template -class Adder> { - public: - using Weight = LogWeightTpl; - - explicit Adder(Weight w = Weight::Zero()) : sum_(w.Value()), c_(0.0) {} - - Weight Add(const Weight &w) { - using Limits = FloatLimits; - const T f = w.Value(); - if (f == Limits::PosInfinity()) { - return Sum(); - } else if (sum_ == Limits::PosInfinity()) { - sum_ = f; - c_ = 0.0; - } else if (f > sum_) { - sum_ = internal::KahanLogSum(sum_, f, &c_); - } else { - sum_ = internal::KahanLogSum(f, sum_, &c_); - } - return Sum(); - } - - Weight Sum() const { return Weight(sum_); } - - void Reset(Weight w = Weight::Zero()) { - sum_ = w.Value(); - c_ = 0.0; - } - - private: - double sum_; - double c_; // Kahan compensation. -}; - -// Real semiring: (+, *, 0, 1). -template -class RealWeightTpl : public FloatWeightTpl { - public: - using typename FloatWeightTpl::ValueType; - using FloatWeightTpl::Value; - using ReverseWeight = RealWeightTpl; - using Limits = FloatLimits; - - RealWeightTpl() noexcept : FloatWeightTpl() {} - - constexpr RealWeightTpl(T f) : FloatWeightTpl(f) {} - - static constexpr RealWeightTpl Zero() { return 0; } - - static constexpr RealWeightTpl One() { return 1; } - - static constexpr RealWeightTpl NoWeight() { return Limits::NumberBad(); } - - static const std::string &Type() { - static const std::string *const type = new std::string( - fst::StrCat("real", FloatWeightTpl::GetPrecisionString())); - return *type; - } - - constexpr bool Member() const { - // The comments for TropicalWeightTpl<>::Member() apply here unchanged. - return Limits::NegInfinity() < Value(); - } - - RealWeightTpl Quantize(float delta = kDelta) const { - if (!Member() || Value() == Limits::PosInfinity()) { - return *this; - } else { - return RealWeightTpl(std::floor(Value() / delta + 0.5F) * delta); - } - } - - constexpr RealWeightTpl Reverse() const { return *this; } - - static constexpr uint64_t Properties() { - return kLeftSemiring | kRightSemiring | kCommutative; - } -}; - -// Single-precision log weight. -using RealWeight = RealWeightTpl; - -// Double-precision log weight. -using Real64Weight = RealWeightTpl; - -namespace internal { - -// a + b = KahanRealSum(a, b, ...). -// Kahan compensated summation provides an error bound that is -// independent of the number of addends. c is the compensation. -inline double KahanRealSum(double a, double b, double *c) { - double y = b - *c; - double t = a + y; - *c = (t - a) - y; - return t; -} - -}; // namespace internal - -// The comments for Times(Tropical...) above apply here unchanged. -template -inline RealWeightTpl Plus(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - const T f1 = w1.Value(); - const T f2 = w2.Value(); - return RealWeightTpl(f1 + f2); -} - -inline RealWeightTpl Plus(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return Plus(w1, w2); -} - -inline RealWeightTpl Plus(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return Plus(w1, w2); -} - -template -inline RealWeightTpl Minus(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - // The comments for Divide(Tropical...) above apply here unchanged. - const T f1 = w1.Value(); - const T f2 = w2.Value(); - return RealWeightTpl(f1 - f2); -} - -inline RealWeightTpl Minus(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return Minus(w1, w2); -} - -inline RealWeightTpl Minus(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return Minus(w1, w2); -} - -// The comments for Times(Tropical...) above apply here similarly. -template -constexpr RealWeightTpl Times(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return RealWeightTpl(w1.Value() * w2.Value()); -} - -constexpr RealWeightTpl Times(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return Times(w1, w2); -} - -constexpr RealWeightTpl Times(const RealWeightTpl &w1, - const RealWeightTpl &w2) { - return Times(w1, w2); -} - -template -constexpr RealWeightTpl Divide(const RealWeightTpl &w1, - const RealWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - using Weight = RealWeightTpl; - return w2.Member() ? Weight(w1.Value() / w2.Value()) : Weight::NoWeight(); -} - -constexpr RealWeightTpl Divide(const RealWeightTpl &w1, - const RealWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -constexpr RealWeightTpl Divide(const RealWeightTpl &w1, - const RealWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -// The comments for Power<>(Tropical...) above apply here unchanged. - -template , - typename std::enable_if_t * = nullptr> -constexpr RealWeightTpl Power(const RealWeightTpl &w, V n) { - using Weight = RealWeightTpl; - return (!w.Member() || internal::IsNan(n)) ? Weight::NoWeight() - : (n == 0 || w == Weight::One()) ? Weight::One() - : Weight(pow(w.Value(), n)); -} - -// Specializes the library-wide template to use the above implementation; rules -// of function template instantiation require this be a full instantiation. - -template <> -constexpr RealWeightTpl Power>( - const RealWeightTpl &weight, size_t n) { - return Power(weight, n); -} - -template <> -constexpr RealWeightTpl Power>( - const RealWeightTpl &weight, size_t n) { - return Power(weight, n); -} - -// Specialization using the Kahan compensated summation. -template -class Adder> { - public: - using Weight = RealWeightTpl; - - explicit Adder(Weight w = Weight::Zero()) : sum_(w.Value()), c_(0.0) {} - - Weight Add(const Weight &w) { - using Limits = FloatLimits; - const T f = w.Value(); - if (f == Limits::PosInfinity()) { - sum_ = f; - } else if (sum_ == Limits::PosInfinity()) { - return sum_; - } else { - sum_ = internal::KahanRealSum(sum_, f, &c_); - } - return Sum(); - } - - Weight Sum() const { return Weight(sum_); } - - void Reset(Weight w = Weight::Zero()) { - sum_ = w.Value(); - c_ = 0.0; - } - - private: - double sum_; - double c_; // Kahan compensation. -}; - -// MinMax semiring: (min, max, inf, -inf). -template -class MinMaxWeightTpl : public FloatWeightTpl { - public: - using typename FloatWeightTpl::ValueType; - using FloatWeightTpl::Value; - using ReverseWeight = MinMaxWeightTpl; - using Limits = FloatLimits; - - MinMaxWeightTpl() noexcept : FloatWeightTpl() {} - - constexpr MinMaxWeightTpl(T f) : FloatWeightTpl(f) {} // NOLINT - - static constexpr MinMaxWeightTpl Zero() { return Limits::PosInfinity(); } - - static constexpr MinMaxWeightTpl One() { return Limits::NegInfinity(); } - - static constexpr MinMaxWeightTpl NoWeight() { return Limits::NumberBad(); } - - static const std::string &Type() { - static const std::string *const type = new std::string( - fst::StrCat("minmax", FloatWeightTpl::GetPrecisionString())); - return *type; - } - - // Fails for IEEE NaN. - constexpr bool Member() const { return !internal::IsNan(Value()); } - - MinMaxWeightTpl Quantize(float delta = kDelta) const { - // If one of infinities, or a NaN. - if (!Member() || Value() == Limits::NegInfinity() || - Value() == Limits::PosInfinity()) { - return *this; - } else { - return MinMaxWeightTpl(std::floor(Value() / delta + 0.5F) * delta); - } - } - - constexpr MinMaxWeightTpl Reverse() const { return *this; } - - static constexpr uint64_t Properties() { - return kLeftSemiring | kRightSemiring | kCommutative | kIdempotent | kPath; - } -}; - -// Single-precision min-max weight. -using MinMaxWeight = MinMaxWeightTpl; - -// Min. -template -constexpr MinMaxWeightTpl Plus(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2) { - return (!w1.Member() || !w2.Member()) ? MinMaxWeightTpl::NoWeight() - : w1.Value() < w2.Value() ? w1 - : w2; -} - -constexpr MinMaxWeightTpl Plus(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2) { - return Plus(w1, w2); -} - -constexpr MinMaxWeightTpl Plus(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2) { - return Plus(w1, w2); -} - -// Max. -template -constexpr MinMaxWeightTpl Times(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2) { - return (!w1.Member() || !w2.Member()) ? MinMaxWeightTpl::NoWeight() - : w1.Value() >= w2.Value() ? w1 - : w2; -} - -constexpr MinMaxWeightTpl Times(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2) { - return Times(w1, w2); -} - -constexpr MinMaxWeightTpl Times(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2) { - return Times(w1, w2); -} - -// Defined only for special cases. -template -constexpr MinMaxWeightTpl Divide(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return w1.Value() >= w2.Value() ? w1 : MinMaxWeightTpl::NoWeight(); -} - -constexpr MinMaxWeightTpl Divide(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -constexpr MinMaxWeightTpl Divide(const MinMaxWeightTpl &w1, - const MinMaxWeightTpl &w2, - DivideType typ = DIVIDE_ANY) { - return Divide(w1, w2, typ); -} - -// Converts to tropical. -template <> -struct WeightConvert { - constexpr TropicalWeight operator()(const LogWeight &w) const { - return w.Value(); - } -}; - -template <> -struct WeightConvert { - constexpr TropicalWeight operator()(const Log64Weight &w) const { - return w.Value(); - } -}; - -// Converts to log. -template <> -struct WeightConvert { - constexpr LogWeight operator()(const TropicalWeight &w) const { - return w.Value(); - } -}; - -template <> -struct WeightConvert { - LogWeight operator()(const RealWeight &w) const { return -log(w.Value()); } -}; - -template <> -struct WeightConvert { - LogWeight operator()(const Real64Weight &w) const { return -log(w.Value()); } -}; - -template <> -struct WeightConvert { - constexpr LogWeight operator()(const Log64Weight &w) const { - return w.Value(); - } -}; - -// Converts to log64. -template <> -struct WeightConvert { - constexpr Log64Weight operator()(const TropicalWeight &w) const { - return w.Value(); - } -}; - -template <> -struct WeightConvert { - Log64Weight operator()(const RealWeight &w) const { return -log(w.Value()); } -}; - -template <> -struct WeightConvert { - Log64Weight operator()(const Real64Weight &w) const { - return -log(w.Value()); - } -}; - -template <> -struct WeightConvert { - constexpr Log64Weight operator()(const LogWeight &w) const { - return w.Value(); - } -}; - -// Converts to real. -template <> -struct WeightConvert { - RealWeight operator()(const LogWeight &w) const { return exp(-w.Value()); } -}; - -template <> -struct WeightConvert { - RealWeight operator()(const Log64Weight &w) const { return exp(-w.Value()); } -}; - -template <> -struct WeightConvert { - constexpr RealWeight operator()(const Real64Weight &w) const { - return w.Value(); - } -}; - -// Converts to real64 -template <> -struct WeightConvert { - Real64Weight operator()(const LogWeight &w) const { return exp(-w.Value()); } -}; - -template <> -struct WeightConvert { - Real64Weight operator()(const Log64Weight &w) const { - return exp(-w.Value()); - } -}; - -template <> -struct WeightConvert { - constexpr Real64Weight operator()(const RealWeight &w) const { - return w.Value(); - } -}; - -// This function object returns random integers chosen from [0, -// num_random_weights). The allow_zero argument determines whether Zero() and -// zero divisors should be returned in the random weight generation. This is -// intended primary for testing. -template -class FloatWeightGenerate { - public: - explicit FloatWeightGenerate( - uint64_t seed = std::random_device()(), bool allow_zero = true, - const size_t num_random_weights = kNumRandomWeights) - : rand_(seed), - allow_zero_(allow_zero), - num_random_weights_(num_random_weights) {} - - Weight operator()() const { - const int sample = std::uniform_int_distribution<>( - 0, num_random_weights_ + allow_zero_ - 1)(rand_); - if (allow_zero_ && sample == num_random_weights_) return Weight::Zero(); - return Weight(sample); - } - - private: - mutable std::mt19937_64 rand_; - const bool allow_zero_; - const size_t num_random_weights_; -}; - -template -class WeightGenerate> - : public FloatWeightGenerate> { - public: - using Weight = TropicalWeightTpl; - using Generate = FloatWeightGenerate; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true, - size_t num_random_weights = kNumRandomWeights) - : Generate(seed, allow_zero, num_random_weights) {} - - Weight operator()() const { return Weight(Generate::operator()()); } -}; - -template -class WeightGenerate> - : public FloatWeightGenerate> { - public: - using Weight = LogWeightTpl; - using Generate = FloatWeightGenerate; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true, - size_t num_random_weights = kNumRandomWeights) - : Generate(seed, allow_zero, num_random_weights) {} - - Weight operator()() const { return Weight(Generate::operator()()); } -}; - -template -class WeightGenerate> - : public FloatWeightGenerate> { - public: - using Weight = RealWeightTpl; - using Generate = FloatWeightGenerate; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true, - size_t num_random_weights = kNumRandomWeights) - : Generate(seed, allow_zero, num_random_weights) {} - - Weight operator()() const { return Weight(Generate::operator()()); } -}; - -// This function object returns random integers chosen from [0, -// num_random_weights). The boolean 'allow_zero' determines whether Zero() and -// zero divisors should be returned in the random weight generation. This is -// intended primary for testing. -template -class WeightGenerate> { - public: - using Weight = MinMaxWeightTpl; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true, - size_t num_random_weights = kNumRandomWeights) - : rand_(seed), - allow_zero_(allow_zero), - num_random_weights_(num_random_weights) {} - - Weight operator()() const { - const int sample = std::uniform_int_distribution<>( - -num_random_weights_, num_random_weights_ + allow_zero_)(rand_); - if (allow_zero_ && sample == 0) { - return Weight::Zero(); - } else if (sample == -num_random_weights_) { - return Weight::One(); - } else { - return Weight(sample); - } - } - - private: - mutable std::mt19937_64 rand_; - const bool allow_zero_; - const size_t num_random_weights_; -}; - -} // namespace fst - -#endif // FST_FLOAT_WEIGHT_H_ diff --git a/contrib/fstlib/fst/fst-decl.h b/contrib/fstlib/fst/fst-decl.h deleted file mode 100644 index aff7508..0000000 --- a/contrib/fstlib/fst/fst-decl.h +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// This file contains declarations of classes in the Fst template library. - -#ifndef FST_FST_DECL_H_ -#define FST_FST_DECL_H_ - -// Do not let Include-What-You-Use suggest this file. - - -#include - -#include -#include // for allocator<> - -#include - -namespace fst { - -// Symbol table and iterator. - -class SymbolTable; - -class SymbolTableIterator; - -// Weight templates and weights. - -template -class FloatWeightTpl; - -template -class TropicalWeightTpl; - -template -class LogWeightTpl; - -template -class MinMaxWeightTpl; - -using FloatWeight = FloatWeightTpl; - -using TropicalWeight = TropicalWeightTpl; - -using LogWeight = LogWeightTpl; - -using MinMaxWeight = MinMaxWeightTpl; - -// Arc templates and arcs. - -template -struct ArcTpl; - -using StdArc = ArcTpl; - -using LogArc = ArcTpl; - -// Stores. - -template -class CompactArcStore; - -template -class DefaultCacheStore; - -// Compactors. - -template > -class CompactArcCompactor; - -// FST templates. - -template > -class CompactFst; - -// The Unsigned type is used to represent indices into the compact arc array. -template , - class CacheStore = DefaultCacheStore> -using CompactArcFst = - CompactFst, - CacheStore>; - -template -class ConstFst; - -template -class EditFst; - -template -class ExpandedFst; - -template -class Fst; - -template -class MutableFst; - -template > -class VectorState; - -template > -class VectorFst; - -template -class DefaultReplaceStateTable; - -// On-the-fly operations. - -template -class ArcSortFst; - -template -class ClosureFst; - -template > -class ComposeFst; - -template -class ConcatFst; - -template -class DeterminizeFst; - -template -class DifferenceFst; - -template -class IntersectFst; - -template -class InvertFst; - -template -class ArcMapFst; - -template -class ProjectFst; - -template -class RandGenFst; - -template -class RelabelFst; - -template , - class Store = DefaultCacheStore> -class ReplaceFst; - -template -class RmEpsilonFst; - -template -class UnionFst; - -// Heap. - -template -class Heap; - -// ArcCompactors. - -template -class AcceptorCompactor; - -template -class StringCompactor; - -template -class UnweightedAcceptorCompactor; - -template -class UnweightedCompactor; - -template -class WeightedStringCompactor; - -// Compact Arc FSTs. - -template -using CompactStringFst = CompactArcFst, U>; - -template -using CompactWeightedStringFst = - CompactArcFst, U>; - -template -using CompactAcceptorFst = CompactArcFst, U>; - -template -using CompactUnweightedFst = CompactArcFst, U>; - -template -using CompactUnweightedAcceptorFst = - CompactArcFst, U>; - -// StdArc aliases for FSTs. - -using StdConstFst = ConstFst; -using StdExpandedFst = ExpandedFst; -using StdFst = Fst; -using StdMutableFst = MutableFst; -using StdVectorFst = VectorFst; - -// StdArc aliases for on-the-fly operations. - -template -using StdArcSortFst = ArcSortFst; - -using StdClosureFst = ClosureFst; - -using StdComposeFst = ComposeFst; - -using StdConcatFst = ConcatFst; - -using StdDeterminizeFst = DeterminizeFst; - -using StdDifferenceFst = DifferenceFst; - -using StdIntersectFst = IntersectFst; - -using StdInvertFst = InvertFst; - -using StdProjectFst = ProjectFst; - -using StdRelabelFst = RelabelFst; - -using StdReplaceFst = ReplaceFst; - -using StdRmEpsilonFst = RmEpsilonFst; - -using StdUnionFst = UnionFst; - -// Filter states. - -template -class IntegerFilterState; - -using CharFilterState = IntegerFilterState; - -using ShortFilterState = IntegerFilterState; // NOLINT - -using IntFilterState = IntegerFilterState; - -// Matchers and filters. - -template -class Matcher; - -template -class NullComposeFilter; - -template -class TrivialComposeFilter; - -template -class SequenceComposeFilter; - -template -class AltSequenceComposeFilter; - -template -class MatchComposeFilter; - -template -class NoMatchComposeFilter; - -} // namespace fst - -#endif // FST_FST_DECL_H_ diff --git a/contrib/fstlib/fst/fst.h b/contrib/fstlib/fst/fst.h deleted file mode 100644 index d233305..0000000 --- a/contrib/fstlib/fst/fst.h +++ /dev/null @@ -1,978 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST abstract base class definition, state and arc iterator interface, and -// suggested base implementation. - -#ifndef FST_FST_H_ -#define FST_FST_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -DECLARE_bool(fst_align); - -namespace fst { - -// Identifies stream data as an FST (and its endianity). -inline constexpr int32_t kFstMagicNumber = 2125659606; - -class FstHeader; -template -class MatcherBase; -template -struct ArcIteratorData; -template -struct StateIteratorData; - -struct FstReadOptions { - // FileReadMode(s) are advisory, there are many conditions than prevent a - // file from being mapped, READ mode will be selected in these cases with - // a warning indicating why it was chosen. - enum FileReadMode { READ, MAP }; - - std::string source; // Where you're reading from. - const FstHeader *header; // Pointer to FST header; if non-zero, use - // this info (don't read a stream header). - const SymbolTable *isymbols; // Pointer to input symbols; if non-zero, use - // this info (read and skip stream isymbols) - const SymbolTable *osymbols; // Pointer to output symbols; if non-zero, use - // this info (read and skip stream osymbols) - FileReadMode mode; // Read or map files (advisory, if possible) - bool read_isymbols; // Read isymbols, if any (default: true). - bool read_osymbols; // Read osymbols, if any (default: true). - - explicit FstReadOptions( - const std::string_view source = "", - const FstHeader * header = nullptr, - const SymbolTable * isymbols = nullptr, - const SymbolTable * osymbols = nullptr); - - explicit FstReadOptions(const std::string_view source, - const SymbolTable *isymbols, - const SymbolTable *osymbols = nullptr); - - // Helper function to convert strings FileReadModes into their enum value. - static FileReadMode ReadMode(std::string_view mode); - - // Outputs a debug string for the FstReadOptions object. - std::string DebugString() const; -}; - -struct FstWriteOptions { - std::string source; // Where you're writing to. - bool write_header; // Write the header? - bool write_isymbols; // Write input symbols? - bool write_osymbols; // Write output symbols? - bool align; // Write data aligned (may fail on pipes)? - bool stream_write; // Avoid seek operations in writing. - - explicit FstWriteOptions(std::string_view source = "", - bool write_header = true, bool write_isymbols = true, - bool write_osymbols = true, - bool align = FST_FLAGS_fst_align, - bool stream_write = false) - : source(source), - write_header(write_header), - write_isymbols(write_isymbols), - write_osymbols(write_osymbols), - align(align), - stream_write(stream_write) {} -}; - -// Header class. -// -// This is the recommended file header representation. - -class FstHeader { - public: - enum Flags { - HAS_ISYMBOLS = 0x1, // Has input symbol table. - HAS_OSYMBOLS = 0x2, // Has output symbol table. - IS_ALIGNED = 0x4, // Memory-aligned (where appropriate). - }; - - FstHeader() = default; - - const std::string &FstType() const { return fsttype_; } - - const std::string &ArcType() const { return arctype_; } - - int32_t Version() const { return version_; } - - uint32_t GetFlags() const { return flags_; } - - uint64_t Properties() const { return properties_; } - - int64_t Start() const { return start_; } - - int64_t NumStates() const { return numstates_; } - - int64_t NumArcs() const { return numarcs_; } - - void SetFstType(std::string_view type) { fsttype_ = std::string(type); } - - void SetArcType(std::string_view type) { arctype_ = std::string(type); } - - void SetVersion(int32_t version) { version_ = version; } - - void SetFlags(uint32_t flags) { flags_ = flags; } - - void SetProperties(uint64_t properties) { properties_ = properties; } - - void SetStart(int64_t start) { start_ = start; } - - void SetNumStates(int64_t numstates) { numstates_ = numstates; } - - void SetNumArcs(int64_t numarcs) { numarcs_ = numarcs; } - - bool Read(std::istream &strm, const std::string &source, bool rewind = false); - - bool Write(std::ostream &strm, std::string_view source) const; - - // Outputs a debug string for the FstHeader object. - std::string DebugString() const; - - private: - std::string fsttype_; // E.g. "vector". - std::string arctype_; // E.g. "standard". - int32_t version_ = 0; // Type version number. - uint32_t flags_ = 0; // File format bits. - uint64_t properties_ = 0; // FST property bits. - int64_t start_ = -1; // Start state. - int64_t numstates_ = 0; // # of states. - int64_t numarcs_ = 0; // # of arcs. -}; - -// Specifies matcher action. -enum MatchType { - MATCH_INPUT = 1, // Match input label. - MATCH_OUTPUT = 2, // Match output label. - MATCH_BOTH = 3, // Match input or output label. - MATCH_NONE = 4, // Match nothing. - MATCH_UNKNOWN = 5 -}; // Otherwise, match type unknown. - -inline constexpr int kNoLabel = -1; // Not a valid label. -inline constexpr int kNoStateId = -1; // Not a valid state ID. - -// A generic FST, templated on the arc definition, with common-demoninator -// methods (use StateIterator and ArcIterator to iterate over its states and -// arcs). Derived classes should be assumed to be thread-unsafe unless -// otherwise specified. -template -class Fst { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - virtual ~Fst() = default; - - // Initial state. - virtual StateId Start() const = 0; - - // State's final weight. - virtual Weight Final(StateId) const = 0; - - // State's arc count. - virtual size_t NumArcs(StateId) const = 0; - - // State's input epsilon count. - virtual size_t NumInputEpsilons(StateId) const = 0; - - // State's output epsilon count. - virtual size_t NumOutputEpsilons(StateId) const = 0; - - // Returns the number of states if it is finite and can be computed in O(1) - // time. Otherwise returns nullopt. - virtual std::optional NumStatesIfKnown() const { - return std::nullopt; - } - - // Property bits. If test = false, return stored properties bits for mask - // (some possibly unknown); if test = true, return property bits for mask - // (computing o.w. unknown). - virtual uint64_t Properties(uint64_t mask, bool test) const = 0; - - // FST type name. - virtual const std::string &Type() const = 0; - - // Gets a copy of this Fst. The copying behaves as follows: - // - // (1) The copying is constant time if safe = false or if safe = true - // and is on an otherwise unaccessed FST. - // - // (2) If safe = true, the copy is thread-safe in that the original - // and copy can be safely accessed (but not necessarily mutated) by - // separate threads. For some FST types, 'Copy(true)' should only be - // called on an FST that has not otherwise been accessed. Behavior is - // otherwise undefined. - // - // (3) If a MutableFst is copied and then mutated, then the original is - // unmodified and vice versa (often by a copy-on-write on the initial - // mutation, which may not be constant time). - virtual Fst *Copy(bool safe = false) const = 0; - - // Reads an FST from an input stream; returns nullptr on error. - static Fst *Read(std::istream &strm, const FstReadOptions &opts) { - FstReadOptions ropts(opts); - FstHeader hdr; - if (ropts.header) { - hdr = *opts.header; - } else { - if (!hdr.Read(strm, opts.source)) return nullptr; - ropts.header = &hdr; - } - const auto &fst_type = hdr.FstType(); - const auto reader = FstRegister::GetRegister()->GetReader(fst_type); - if (!reader) { - LOG(ERROR) << "Fst::Read: Unknown FST type " << fst_type - << " (arc type = " << Arc::Type() << "): " << ropts.source; - return nullptr; - } - return reader(strm, ropts); - } - - // Reads an FST from a file; returns nullptr on error. An empty source - // results in reading from standard input. - static Fst *Read(const std::string &source) { - if (!source.empty()) { - std::ifstream strm(source, - std::ios_base::in | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "Fst::Read: Can't open file: " << source; - return nullptr; - } - return Read(strm, FstReadOptions(source)); - } else { - return Read(std::cin, FstReadOptions("standard input")); - } - } - - // Writes an FST to an output stream; returns false on error. - virtual bool Write(std::ostream &strm, const FstWriteOptions &opts) const { - LOG(ERROR) << "Fst::Write: No write stream method for " << Type() - << " FST type"; - return false; - } - - // Writes an FST to a file; returns false on error; an empty source - // results in writing to standard output. - virtual bool Write(const std::string &source) const { - LOG(ERROR) << "Fst::Write: No write source method for " << Type() - << " FST type"; - return false; - } - - // Some Fst implementations support - // template - // static bool Fst1::WriteFst(const Fst2 &fst2, ...); - // which is equivalent to Fst1(fst2).Write(...), but uses less memory. - // WriteFst is not part of the general Fst interface. - - // Returns input label symbol table; return nullptr if not specified. - virtual const SymbolTable *InputSymbols() const = 0; - - // Return output label symbol table; return nullptr if not specified. - virtual const SymbolTable *OutputSymbols() const = 0; - - // For generic state iterator construction (not normally called directly by - // users). Does not copy the FST. - virtual void InitStateIterator(StateIteratorData *data) const = 0; - - // For generic arc iterator construction (not normally called directly by - // users). Does not copy the FST. - virtual void InitArcIterator(StateId s, ArcIteratorData *data) const = 0; - - // For generic matcher construction (not normally called directly by users). - // Does not copy the FST. - virtual MatcherBase *InitMatcher(MatchType match_type) const; - - protected: - bool WriteFile(const std::string &source) const { - if (!source.empty()) { - std::ofstream strm(source, - std::ios_base::out | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "Fst::WriteFile: Can't open file: " << source; - return false; - } - if (!Write(strm, FstWriteOptions(source))) { - LOG(ERROR) << "Fst::WriteFile: Write failed: " << source; - return false; - } - return true; - } else { - return Write(std::cout, FstWriteOptions("standard output")); - } - } -}; - -// A useful alias when using StdArc. -using StdFst = Fst; - -// State and arc iterator definitions. -// -// State iterator interface templated on the Arc definition; used for -// StateIterator specializations returned by the InitStateIterator FST method. -template -class StateIteratorBase { - public: - using StateId = typename Arc::StateId; - - virtual ~StateIteratorBase() = default; - - // End of iterator? - virtual bool Done() const = 0; - // Returns current state (when !Done()). - virtual StateId Value() const = 0; - // Advances to next state (when !Done()). - virtual void Next() = 0; - // Resets to initial condition. - virtual void Reset() = 0; -}; - -// StateIterator initialization data. - -template -struct StateIteratorData { - using StateId = typename Arc::StateId; - - // Specialized iterator if non-null. - std::unique_ptr> base; - // Otherwise, the total number of states. - StateId nstates = 0; - - StateIteratorData() = default; - - StateIteratorData(const StateIteratorData &) = delete; - StateIteratorData &operator=(const StateIteratorData &) = delete; -}; - -// Generic state iterator, templated on the FST definition (a wrapper -// around a pointer to a specific one). Here is a typical use: -// -// for (StateIterator siter(fst); -// !siter.Done(); -// siter.Next()) { -// StateId s = siter.Value(); -// ... -// } -// There is no copying of the FST. -// -// Specializations may exist for some FST types. -// StateIterators are thread-unsafe unless otherwise specified. -template -class StateIterator { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - - explicit StateIterator(const FST &fst) { - fst.InitStateIterator(&data_); - } - - bool Done() const { - return data_.base ? data_.base->Done() : s_ >= data_.nstates; - } - - StateId Value() const { return data_.base ? data_.base->Value() : s_; } - - void Next() { - if (data_.base) { - data_.base->Next(); - } else { - ++s_; - } - } - - void Reset() { - if (data_.base) { - data_.base->Reset(); - } else { - s_ = 0; - } - } - - private: - StateIteratorData data_; - StateId s_ = 0; -}; - -// Flags to control the behavior on an arc iterator via SetFlags(). -// Value() gives valid ilabel. -inline constexpr uint8_t kArcILabelValue = 0x01; -// Value() call gives valid olabel. -inline constexpr uint8_t kArcOLabelValue = 0x02; -// Value() call gives valid weight. -inline constexpr uint8_t kArcWeightValue = 0x04; -// Value() call gives valid nextstate. -inline constexpr uint8_t kArcNextStateValue = 0x08; -// Arcs need not be cached. -inline constexpr uint8_t kArcNoCache = 0x10; -inline constexpr uint8_t kArcValueFlags = - kArcILabelValue | kArcOLabelValue | kArcWeightValue | kArcNextStateValue; -inline constexpr uint8_t kArcFlags = kArcValueFlags | kArcNoCache; - -// Arc iterator interface, templated on the arc definition; used for arc -// iterator specializations that are returned by the InitArcIterator FST method. -template -class ArcIteratorBase { - public: - using StateId = typename Arc::StateId; - - virtual ~ArcIteratorBase() = default; - - // End of iterator? - virtual bool Done() const = 0; - // Returns current arc (when !Done()). - virtual const Arc &Value() const = 0; - // Advances to next arc (when !Done()). - virtual void Next() = 0; - // Returns current position. - virtual size_t Position() const = 0; - // Returns to initial condition. - virtual void Reset() = 0; - // Advances to arbitrary arc by position. - virtual void Seek(size_t) = 0; - // Returns current behavorial flags, a bitmask of kArcFlags. - virtual uint8_t Flags() const = 0; - // Sets behavorial flags, a bitmask of kArcFlags. - virtual void SetFlags(uint8_t, uint8_t) = 0; -}; - -// ArcIterator initialization data. -template -struct ArcIteratorData { - ArcIteratorData() = default; - - ArcIteratorData(const ArcIteratorData &) = delete; - - ArcIteratorData &operator=(const ArcIteratorData &) = delete; - - std::unique_ptr> - base; // Specialized iterator if non-null. - const Arc *arcs = nullptr; // O.w. arcs pointer - size_t narcs = 0; // ... and arc count. - int *ref_count = nullptr; // ... and a reference count of the - // `narcs`-length `arcs` array if non-null. -}; - -// Generic arc iterator, templated on the FST definition (a wrapper around a -// pointer to a specific one). Here is a typical use: -// -// for (ArcIterator aiter(fst, s); -// !aiter.Done(); -// aiter.Next()) { -// StdArc &arc = aiter.Value(); -// ... -// } -// There is no copying of the FST. -// -// Specializations may exist for some FST types. -// ArcIterators are thread-unsafe unless otherwise specified. -template -class ArcIterator { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - - ArcIterator(const FST &fst, StateId s) { - fst.InitArcIterator(s, &data_); - } - - explicit ArcIterator(const ArcIteratorData &data) = delete; - - ~ArcIterator() { - if (data_.ref_count) { - --(*data_.ref_count); - } - } - - bool Done() const { - return data_.base ? data_.base->Done() : i_ >= data_.narcs; - } - - const Arc &Value() const { - return data_.base ? data_.base->Value() : data_.arcs[i_]; - } - - void Next() { - if (data_.base) { - data_.base->Next(); - } else { - ++i_; - } - } - - void Reset() { - if (data_.base) { - data_.base->Reset(); - } else { - i_ = 0; - } - } - - void Seek(size_t a) { - if (data_.base) { - data_.base->Seek(a); - } else { - i_ = a; - } - } - - size_t Position() const { return data_.base ? data_.base->Position() : i_; } - - uint8_t Flags() const { - return data_.base ? data_.base->Flags() : kArcValueFlags; - } - - void SetFlags(uint8_t flags, uint8_t mask) { - if (data_.base) data_.base->SetFlags(flags, mask); - } - - private: - ArcIteratorData data_; - size_t i_ = 0; -}; - -} // namespace fst - -// ArcIterator placement operator new and destroy function; new needs to be in -// the global namespace. - -template -void *operator new(size_t size, - fst::MemoryPool> *pool) { - return pool->Allocate(); -} - -namespace fst { - -template -void Destroy(ArcIterator *aiter, MemoryPool> *pool) { - if (aiter) { - aiter->~ArcIterator(); - pool->Free(aiter); - } -} - -// Matcher definitions. - -template -MatcherBase *Fst::InitMatcher(MatchType match_type) const { - return nullptr; // One should just use the default matcher. -} - -// FST accessors, useful in high-performance applications. - -namespace internal { - -// General case, requires non-abstract, 'final' methods. Use for inlining. - -template -inline typename F::Arc::Weight Final(const F &fst, typename F::Arc::StateId s) { - return fst.F::Final(s); -} - -template -inline ssize_t NumArcs(const F &fst, typename F::Arc::StateId s) { - return fst.F::NumArcs(s); -} - -template -inline ssize_t NumInputEpsilons(const F &fst, typename F::Arc::StateId s) { - return fst.F::NumInputEpsilons(s); -} - -template -inline ssize_t NumOutputEpsilons(const F &fst, typename F::Arc::StateId s) { - return fst.F::NumOutputEpsilons(s); -} - -// Fst case, abstract methods. - -template -inline typename Arc::Weight Final(const Fst &fst, - typename Arc::StateId s) { - return fst.Final(s); -} - -template -inline size_t NumArcs(const Fst &fst, typename Arc::StateId s) { - return fst.NumArcs(s); -} - -template -inline size_t NumInputEpsilons(const Fst &fst, typename Arc::StateId s) { - return fst.NumInputEpsilons(s); -} - -template -inline size_t NumOutputEpsilons(const Fst &fst, typename Arc::StateId s) { - return fst.NumOutputEpsilons(s); -} - -// FST implementation base. -// -// This is the recommended FST implementation base class. It will handle -// reference counts, property bits, type information and symbols. -// -// Users are discouraged, but not prohibited, from subclassing this outside the -// FST library. -// -// This class is thread-compatible except for the const SetProperties -// overload. Derived classes should be assumed to be thread-unsafe unless -// otherwise specified. Derived-class copy constructors must produce a -// thread-safe copy. -template -class FstImpl { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - FstImpl() = default; - - FstImpl(const FstImpl &impl) - : properties_(impl.properties_.load(std::memory_order_relaxed)), - type_(impl.type_), - isymbols_(impl.isymbols_ ? impl.isymbols_->Copy() : nullptr), - osymbols_(impl.osymbols_ ? impl.osymbols_->Copy() : nullptr) {} - - FstImpl(FstImpl &&impl) noexcept; - - virtual ~FstImpl() = default; - - FstImpl &operator=(const FstImpl &impl) { - properties_.store(impl.properties_.load(std::memory_order_relaxed), - std::memory_order_relaxed); - type_ = impl.type_; - isymbols_.reset(impl.isymbols_ ? impl.isymbols_->Copy() : nullptr); - osymbols_.reset(impl.osymbols_ ? impl.osymbols_->Copy() : nullptr); - return *this; - } - - FstImpl &operator=(FstImpl &&impl) noexcept; - - const std::string &Type() const { return type_; } - - void SetType(std::string_view type) { type_ = std::string(type); } - - virtual uint64_t Properties() const { - return properties_.load(std::memory_order_relaxed); - } - - virtual uint64_t Properties(uint64_t mask) const { - return properties_.load(std::memory_order_relaxed) & mask; - } - - void SetProperties(uint64_t props) { - uint64_t properties = properties_.load(std::memory_order_relaxed); - properties &= kError; // kError can't be cleared. - properties |= props; - properties_.store(properties, std::memory_order_relaxed); - } - - void SetProperties(uint64_t props, uint64_t mask) { - // Unlike UpdateProperties, does not require compatibility between props - // and properties_, since it may be used to update properties after - // a mutation. - uint64_t properties = properties_.load(std::memory_order_relaxed); - properties &= ~mask | kError; // kError can't be cleared. - properties |= props & mask; - properties_.store(properties, std::memory_order_relaxed); - } - - // Allows (only) setting error bit on const FST implementations. - void SetProperties(uint64_t props, uint64_t mask) const { - if (mask != kError) { - FSTERROR() << "FstImpl::SetProperties() const: Can only set kError"; - } - properties_.fetch_or(kError, std::memory_order_relaxed); - } - - // Sets the subset of the properties that have changed, in a thread-safe - // manner via atomic bitwise-or.. - void UpdateProperties(uint64_t props, uint64_t mask) { - // If properties_ and props are compatible (for example kAcceptor and - // kNoAcceptor cannot both be set), the props can be or-ed in. - // Compatibility is ensured if props comes from ComputeProperties - // and properties_ is set correctly initially. However - // relying on properties to be set correctly is too large an - // assumption, as many places set them incorrectly. - // Therefore, we or in only the newly discovered properties. - // These cannot become inconsistent, but this means that - // incorrectly set properties will remain incorrect. - const uint64_t properties = properties_.load(std::memory_order_relaxed); - DCHECK(internal::CompatProperties(properties, props)); - const uint64_t old_props = properties & mask; - const uint64_t old_mask = internal::KnownProperties(old_props); - const uint64_t discovered_mask = mask & ~old_mask; - const uint64_t discovered_props = props & discovered_mask; - // It is always correct to or these bits in, but do this only when - // necessary to avoid extra stores and possible cache flushes. - if (discovered_props != 0) { - properties_.fetch_or(discovered_props, std::memory_order_relaxed); - } - } - - const SymbolTable *InputSymbols() const { return isymbols_.get(); } - - const SymbolTable *OutputSymbols() const { return osymbols_.get(); } - - SymbolTable *InputSymbols() { return isymbols_.get(); } - - SymbolTable *OutputSymbols() { return osymbols_.get(); } - - void SetInputSymbols(const SymbolTable *isyms) { - isymbols_.reset(isyms ? isyms->Copy() : nullptr); - } - - void SetOutputSymbols(const SymbolTable *osyms) { - osymbols_.reset(osyms ? osyms->Copy() : nullptr); - } - - // Reads header and symbols from input stream, initializes FST, and returns - // the header. If opts.header is non-null, skips reading and uses the option - // value instead. If opts.[io]symbols is non-null, reads in (if present), but - // uses the option value. - bool ReadHeader(std::istream &strm, const FstReadOptions &opts, - int min_version, FstHeader *hdr); - - // Writes header and symbols to output stream. If opts.header is false, skips - // writing header. If opts.[io]symbols is false, skips writing those symbols. - // This method is needed for implementations that implement Write methods. - void WriteHeader(std::ostream &strm, const FstWriteOptions &opts, int version, - FstHeader *hdr) const { - if (opts.write_header) { - hdr->SetFstType(type_); - hdr->SetArcType(Arc::Type()); - hdr->SetVersion(version); - hdr->SetProperties(properties_.load(std::memory_order_relaxed)); - int32_t file_flags = 0; - if (isymbols_ && opts.write_isymbols) { - file_flags |= FstHeader::HAS_ISYMBOLS; - } - if (osymbols_ && opts.write_osymbols) { - file_flags |= FstHeader::HAS_OSYMBOLS; - } - if (opts.align) file_flags |= FstHeader::IS_ALIGNED; - hdr->SetFlags(file_flags); - hdr->Write(strm, opts.source); - } - if (isymbols_ && opts.write_isymbols) isymbols_->Write(strm); - if (osymbols_ && opts.write_osymbols) osymbols_->Write(strm); - } - - // Writes out header and symbols to output stream. If opts.header is false, - // skips writing header. If opts.[io]symbols is false, skips writing those - // symbols. `type` is the FST type being written. This method is used in the - // cross-type serialization methods Fst::WriteFst. - static void WriteFstHeader(const Fst &fst, std::ostream &strm, - const FstWriteOptions &opts, int version, - std::string_view type, uint64_t properties, - FstHeader *hdr) { - if (opts.write_header) { - hdr->SetFstType(type); - hdr->SetArcType(Arc::Type()); - hdr->SetVersion(version); - hdr->SetProperties(properties); - int32_t file_flags = 0; - if (fst.InputSymbols() && opts.write_isymbols) { - file_flags |= FstHeader::HAS_ISYMBOLS; - } - if (fst.OutputSymbols() && opts.write_osymbols) { - file_flags |= FstHeader::HAS_OSYMBOLS; - } - if (opts.align) file_flags |= FstHeader::IS_ALIGNED; - hdr->SetFlags(file_flags); - hdr->Write(strm, opts.source); - } - if (fst.InputSymbols() && opts.write_isymbols) { - fst.InputSymbols()->Write(strm); - } - if (fst.OutputSymbols() && opts.write_osymbols) { - fst.OutputSymbols()->Write(strm); - } - } - - // In serialization routines where the header cannot be written until after - // the machine has been serialized, this routine can be called to seek to the - // beginning of the file an rewrite the header with updated fields. It - // repositions the file pointer back at the end of the file. Returns true on - // success, false on failure. - static bool UpdateFstHeader(const Fst &fst, std::ostream &strm, - const FstWriteOptions &opts, int version, - std::string_view type, uint64_t properties, - FstHeader *hdr, size_t header_offset) { - strm.seekp(header_offset); - if (!strm) { - LOG(ERROR) << "Fst::UpdateFstHeader: Write failed: " << opts.source; - return false; - } - WriteFstHeader(fst, strm, opts, version, type, properties, hdr); - if (!strm) { - LOG(ERROR) << "Fst::UpdateFstHeader: Write failed: " << opts.source; - return false; - } - strm.seekp(0, std::ios_base::end); - if (!strm) { - LOG(ERROR) << "Fst::UpdateFstHeader: Write failed: " << opts.source; - return false; - } - return true; - } - - protected: - // Use atomic so that UpdateProperties() can be thread-safe. - // This is always used with memory_order_relaxed because it's only used - // as a cache and not used to synchronize other operations. - mutable std::atomic properties_ = 0; // Property bits. - - private: - std::string type_ = "null"; // Unique name of FST class. - std::unique_ptr isymbols_; - std::unique_ptr osymbols_; -}; - -template -inline FstImpl::FstImpl(FstImpl &&) noexcept = default; - -template -inline FstImpl &FstImpl::operator=(FstImpl &&) noexcept = - default; - -template -bool FstImpl::ReadHeader(std::istream &strm, const FstReadOptions &opts, - int min_version, FstHeader *hdr) { - if (opts.header) { - *hdr = *opts.header; - } else if (!hdr->Read(strm, opts.source)) { - return false; - } - VLOG(2) << "FstImpl::ReadHeader: source: " << opts.source - << ", fst_type: " << hdr->FstType() << ", arc_type: " << Arc::Type() - << ", version: " << hdr->Version() << ", flags: " << hdr->GetFlags(); - if (hdr->FstType() != type_) { - LOG(ERROR) << "FstImpl::ReadHeader: FST not of type " << type_ << ", found " - << hdr->FstType() << ": " << opts.source; - return false; - } - if (hdr->ArcType() != Arc::Type()) { - LOG(ERROR) << "FstImpl::ReadHeader: Arc not of type " << Arc::Type() - << ", found " << hdr->ArcType() << ": " << opts.source; - return false; - } - if (hdr->Version() < min_version) { - LOG(ERROR) << "FstImpl::ReadHeader: Obsolete " << type_ << " FST version " - << hdr->Version() << ", min_version=" << min_version << ": " - << opts.source; - return false; - } - properties_.store(hdr->Properties(), std::memory_order_relaxed); - if (hdr->GetFlags() & FstHeader::HAS_ISYMBOLS) { - isymbols_.reset(SymbolTable::Read(strm, opts.source)); - } - // Deletes input symbol table. - if (!opts.read_isymbols) SetInputSymbols(nullptr); - if (hdr->GetFlags() & FstHeader::HAS_OSYMBOLS) { - osymbols_.reset(SymbolTable::Read(strm, opts.source)); - } - // Deletes output symbol table. - if (!opts.read_osymbols) SetOutputSymbols(nullptr); - if (opts.isymbols) { - isymbols_.reset(opts.isymbols->Copy()); - } - if (opts.osymbols) { - osymbols_.reset(opts.osymbols->Copy()); - } - return true; -} - -} // namespace internal - -// Converts FSTs by casting their implementations, where this makes sense -// (which excludes implementations with weight-dependent virtual methods). -// Must be a friend of the FST classes involved (currently the concrete FSTs: -// ConstFst, CompactFst, and VectorFst). This can only be safely used for arc -// types that have identical storage characteristics. As with an FST -// copy constructor and Copy() method, this is a constant time operation -// (but subject to copy-on-write if it is a MutableFst and modified). -template -void Cast(const IFST &ifst, OFST *ofst) { - using OImpl = typename OFST::Impl; - ofst->impl_ = std::shared_ptr( - ifst.impl_, reinterpret_cast(ifst.impl_.get())); -} - -// FST serialization. - -template -std::string FstToString( - const Fst &fst, - const FstWriteOptions &options = FstWriteOptions("FstToString")) { - std::ostringstream ostrm; - fst.Write(ostrm, options); - return ostrm.str(); -} - -template -void FstToString(const Fst &fst, std::string *result) { - *result = FstToString(fst); -} - -template -void FstToString(const Fst &fst, std::string *result, - const FstWriteOptions &options) { - *result = FstToString(fst, options); -} - -template -Fst *StringToFst(std::string_view s) { - std::istringstream istrm((std::string(s))); - return Fst::Read(istrm, FstReadOptions("StringToFst")); -} - -} // namespace fst - -#endif // FST_FST_H_ diff --git a/contrib/fstlib/fst/fstlib.h b/contrib/fstlib/fst/fstlib.h deleted file mode 100644 index 78e157e..0000000 --- a/contrib/fstlib/fst/fstlib.h +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// This is a library for constructing, combining, optimizing, and searching -// "weighted finite-state transducers" (FSTs). Weighted finite-state transducers -// are automata where each transition has an input label, an output label, and a -// weight. The more familiar finite-state acceptor is represented as a -// transducer with each transition's input and output the same. Finite-state -// acceptors are used to represent sets of strings (specifically, "regular" or -// "rational sets"); finite-state transducers are used to represent binary -// relations between pairs of strings (specifically, "rational transductions"). -// The weights can be used to represent the cost of taking a particular -// transition. -// -// In this library, transducers are templated on the Arc (transition) -// definition, which allows changing the label, weight, and state ID sets. -// Labels and state IDs are restricted to signed integral types but the weight -// can be an arbitrary type whose members satisfy certain algebraic ("semiring") -// properties. -// -// This convenience file includes all other FST header files. - -#ifndef FST_FSTLIB_H_ -#define FST_FSTLIB_H_ - -// Do not let Include-What-You-Use suggest this file. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif // FST_FSTLIB_H_ diff --git a/contrib/fstlib/fst/generic-register.h b/contrib/fstlib/fst/generic-register.h deleted file mode 100644 index d95d095..0000000 --- a/contrib/fstlib/fst/generic-register.h +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. - -#ifndef FST_GENERIC_REGISTER_H_ -#define FST_GENERIC_REGISTER_H_ - -#include - -#include -#include -#include -#ifndef FST_NO_DYNAMIC_LINKING -#include -#endif -#include -#include - -#include - -// Generic class representing a globally-stored correspondence between -// objects of KeyType and EntryType. -// -// KeyType must: -// -// * be such as can be stored as a key in a std::map<>. -// -// EntryType must be default constructible. -// -// The third template parameter should be the type of a subclass of this class -// (think CRTP). This is to allow GetRegister() to instantiate and return an -// object of the appropriate type. - -namespace fst { - -namespace internal { -template -struct KeyLookupReferenceType { - using type = const T &; -}; - -template <> -struct KeyLookupReferenceType { - using type = std::string_view; -}; -} // namespace internal - -template -class GenericRegister { - public: - using Key = KeyType; - using KeyLookupRef = typename internal::KeyLookupReferenceType::type; - using Entry = EntryType; - - static RegisterType *GetRegister() { - static auto reg = new RegisterType; - return reg; - } - - void SetEntry(const KeyType &key, const EntryType &entry) { - MutexLock l(®ister_lock_); - register_table_.emplace(key, entry); - } - - EntryType GetEntry(KeyLookupRef key) const { - const auto *entry = LookupEntry(key); - if (entry) { - return *entry; - } else { - return LoadEntryFromSharedObject(key); - } - } - - virtual ~GenericRegister() = default; - - protected: - // Override this if you want to be able to load missing definitions from - // shared object files. - virtual EntryType LoadEntryFromSharedObject(KeyLookupRef key) const { -#ifdef FST_NO_DYNAMIC_LINKING - return EntryType(); -#else - const auto so_filename = ConvertKeyToSoFilename(key); - void *handle = dlopen(so_filename.c_str(), RTLD_LAZY); - if (handle == nullptr) { - LOG(ERROR) << "GenericRegister::GetEntry: " << dlerror(); - return EntryType(); - } -#ifdef RUN_MODULE_INITIALIZERS - RUN_MODULE_INITIALIZERS(); -#endif - // We assume that the DSO constructs a static object in its global scope - // that does the registration. Thus we need only load it, not call any - // methods. - const auto *entry = this->LookupEntry(key); - if (entry == nullptr) { - LOG(ERROR) << "GenericRegister::GetEntry: " - << "lookup failed in shared object: " << so_filename; - return EntryType(); - } - return *entry; -#endif // FST_NO_DYNAMIC_LINKING - } - - // Override this to define how to turn a key into an SO filename. - virtual std::string ConvertKeyToSoFilename(KeyLookupRef key) const = 0; - - virtual const EntryType *LookupEntry(KeyLookupRef key) const { - MutexLock l(®ister_lock_); - if (const auto it = register_table_.find(key); - it != register_table_.end()) { - return &it->second; - } else { - return nullptr; - } - } - - private: - mutable Mutex register_lock_; - std::map> register_table_; -}; - -// Generic register-er class capable of creating new register entries in the -// given RegisterType template parameter. This type must define types Key and -// Entry, and have appropriate static GetRegister() and instance SetEntry() -// functions. An easy way to accomplish this is to have RegisterType be the -// type of a subclass of GenericRegister. -template -class GenericRegisterer { - public: - using Key = typename RegisterType::Key; - using Entry = typename RegisterType::Entry; - - GenericRegisterer(Key key, Entry entry) { - RegisterType::GetRegister()->SetEntry(key, entry); - } -}; - -} // namespace fst - -#endif // FST_GENERIC_REGISTER_H_ diff --git a/contrib/fstlib/fst/heap.h b/contrib/fstlib/fst/heap.h deleted file mode 100644 index 9cbde1e..0000000 --- a/contrib/fstlib/fst/heap.h +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Implementation of a heap as in STL, but allows tracking positions in heap -// using a key. The key can be used to do an in-place update of values in the -// heap. - -#ifndef FST_HEAP_H_ -#define FST_HEAP_H_ - -#include -#include - -#include -#include - -namespace fst { - -// A templated heap implementation that supports in-place update of values. -// -// The templated heap implementation is a little different from the STL -// priority_queue and the *_heap operations in STL. This heap supports -// indexing of values in the heap via an associated key. -// -// Each value is internally associated with a key which is returned to the -// calling functions on heap insert. This key can be used to later update -// the specific value in the heap. -// -// T: the element type of the hash. It can be POD, Data or a pointer to Data. -// Compare: comparison functor for determining min-heapness. -template -class Heap { - public: - using Value = T; - - static constexpr int kNoKey = -1; - - // Initializes with a specific comparator. - explicit Heap(Compare comp = Compare()) : comp_(comp), size_(0) {} - - // Inserts a value into the heap. - int Insert(const Value &value) { - if (size_ < values_.size()) { - values_[size_] = value; - pos_[key_[size_]] = size_; - } else { - values_.push_back(value); - pos_.push_back(size_); - key_.push_back(size_); - } - ++size_; - return Insert(value, size_ - 1); - } - - // Updates a value at position given by the key. The pos_ array is first - // indexed by the key. The position gives the position in the heap array. - // Once we have the position we can then use the standard heap operations - // to calculate the parent and child positions. - void Update(int key, const Value &value) { - const auto i = pos_[key]; - const bool is_better = comp_(value, values_[Parent(i)]); - values_[i] = value; - if (is_better) { - Insert(value, i); - } else { - Heapify(i); - } - } - - // Returns the least value. - Value Pop() { - DCHECK(!Empty()); - Value top = values_.front(); - Swap(0, size_ - 1); - size_--; - Heapify(0); - return top; - } - - // Returns the least value w.r.t. the comparison function from the - // heap. - const Value &Top() const { - DCHECK(!Empty()); - return values_.front(); - } - - // Returns the element for the given key. - const Value &Get(int key) const { - DCHECK_LT(key, pos_.size()); - return values_[pos_[key]]; - } - - // Checks if the heap is empty. - bool Empty() const { return size_ == 0; } - - void Clear() { size_ = 0; } - - int Size() const { return size_; } - - void Reserve(int size) { - values_.reserve(size); - pos_.reserve(size); - key_.reserve(size); - } - - const Compare &GetCompare() const { return comp_; } - - private: - // The following private routines are used in a supportive role - // for managing the heap and keeping the heap properties. - - // Computes left child of parent. - static int Left(int i) { - return 2 * (i + 1) - 1; // 0 -> 1, 1 -> 3 - } - - // Computes right child of parent. - static int Right(int i) { - return 2 * (i + 1); // 0 -> 2, 1 -> 4 - } - - // Given a child computes parent. - static int Parent(int i) { - return (i - 1) / 2; // 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 1, 4 -> 1, ... - } - - // Swaps a child and parent. Use to move element up/down tree. Note the use of - // a little trick here. When we swap we need to swap: - // - // - the value - // - the associated keys - // - the position of the value in the heap - void Swap(int j, int k) { - const auto tkey = key_[j]; - pos_[key_[j] = key_[k]] = j; - pos_[key_[k] = tkey] = k; - using std::swap; - swap(values_[j], values_[k]); - } - - // Heapifies the subtree rooted at index i. - void Heapify(int i) { - const auto l = Left(i); - const auto r = Right(i); - auto largest = (l < size_ && comp_(values_[l], values_[i])) ? l : i; - if (r < size_ && comp_(values_[r], values_[largest])) largest = r; - if (largest != i) { - Swap(i, largest); - Heapify(largest); - } - } - - // Inserts (updates) element at subtree rooted at index i. - int Insert(const Value &value, int i) { - int p; - while (i > 0 && !comp_(values_[p = Parent(i)], value)) { - Swap(i, p); - i = p; - } - return key_[i]; - } - - private: - const Compare comp_; - - std::vector pos_; - std::vector key_; - std::vector values_; - int size_; -}; - -} // namespace fst - -#endif // FST_HEAP_H_ diff --git a/contrib/fstlib/fst/icu.h b/contrib/fstlib/fst/icu.h deleted file mode 100644 index bb93e21..0000000 --- a/contrib/fstlib/fst/icu.h +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// This library implements an unrestricted Thompson/Pike UTF-8 parser and -// serializer. UTF-8 is a restricted subset of this byte stream encoding. For -// a description of the encoding details, see: -// -// http://en.wikipedia.org/wiki/UTF-8 - -#ifndef FST_ICU_H_ -#define FST_ICU_H_ - -#include -#include -#include -#include - -#include -#include - -namespace fst { - -// Trivial function to copy bytestrings into vectors of labels, truncating -// if necessary. It is possible to use this sensibly with as little as 8 bits -// of Label precision. This returns `true` deterministically for compatibility. -template -bool ByteStringToLabels(std::string_view str, std::vector { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using ComposeFst::CreateBase; - using ComposeFst::CreateBase1; - using ComposeFst::Properties; - - IntersectFst(const Fst &fst1, const Fst &fst2, - const CacheOptions &opts = CacheOptions()) - : ComposeFst(CreateBase(fst1, fst2, opts)) { - const bool acceptors = - fst1.Properties(kAcceptor, true) && fst2.Properties(kAcceptor, true); - if (!acceptors) { - FSTERROR() << "IntersectFst: Input FSTs are not acceptors"; - GetMutableImpl()->SetProperties(kError); - } - } - - template - IntersectFst(const Fst &fst1, const Fst &fst2, - const IntersectFstOptions &opts) - : ComposeFst(CreateBase1(fst1, fst2, opts)) { - const bool acceptors = - fst1.Properties(kAcceptor, true) && fst2.Properties(kAcceptor, true); - if (!acceptors) { - FSTERROR() << "IntersectFst: input FSTs are not acceptors"; - GetMutableImpl()->SetProperties(kError); - } - } - - // See Fst<>::Copy() for doc. - IntersectFst(const IntersectFst &fst, bool safe = false) - : ComposeFst(fst, safe) {} - - // Get a copy of this IntersectFst. See Fst<>::Copy() for further doc. - IntersectFst *Copy(bool safe = false) const override { - return new IntersectFst(*this, safe); - } - - private: - using ImplToFst>::GetImpl; - using ImplToFst>::GetMutableImpl; -}; - -// Specialization for IntersectFst. -template -class StateIterator> : public StateIterator> { - public: - explicit StateIterator(const IntersectFst &fst) - : StateIterator>(fst) {} -}; - -// Specialization for IntersectFst. -template -class ArcIterator> : public ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const IntersectFst &fst, StateId s) - : ArcIterator>(fst, s) {} -}; - -// Useful alias when using StdArc. -using StdIntersectFst = IntersectFst; - -// Computes the intersection (Hadamard product) of two FSAs. This version -// writes the intersection to an output MurableFst. Only strings that are in -// both automata are retained in the result. -// -// The two arguments must be acceptors. One of the arguments must be -// label-sorted. -// -// Complexity: same as Compose. -// -// Caveats: same as Compose. -template -void Intersect(const Fst &ifst1, const Fst &ifst2, - MutableFst *ofst, - const IntersectOptions &opts = IntersectOptions()) { - using M = Matcher>; - // In each case, we cache only the last state for fastest copy. - switch (opts.filter_type) { - case AUTO_FILTER: { - CacheOptions nopts; - nopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, nopts); - break; - } - case SEQUENCE_FILTER: { - IntersectFstOptions iopts; - iopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, iopts); - break; - } - case ALT_SEQUENCE_FILTER: { - IntersectFstOptions> iopts; - iopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, iopts); - break; - } - case MATCH_FILTER: { - IntersectFstOptions> iopts; - iopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, iopts); - break; - } - case NO_MATCH_FILTER: { - IntersectFstOptions> iopts; - iopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, iopts); - break; - } - case NULL_FILTER: { - IntersectFstOptions> iopts; - iopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, iopts); - break; - } - case TRIVIAL_FILTER: { - IntersectFstOptions> iopts; - iopts.gc_limit = 0; - *ofst = IntersectFst(ifst1, ifst2, iopts); - break; - } - } - if (opts.connect) Connect(ofst); -} - -} // namespace fst - -#endif // FST_INTERSECT_H_ diff --git a/contrib/fstlib/fst/interval-set.h b/contrib/fstlib/fst/interval-set.h deleted file mode 100644 index d33a0bb..0000000 --- a/contrib/fstlib/fst/interval-set.h +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to represent and operate on sets of intervals. - -#ifndef FST_INTERVAL_SET_H_ -#define FST_INTERVAL_SET_H_ - -#include -#include -#include -#include -#include -#include - -#include - -namespace fst { - -// Half-open integral interval [a, b) of signed integers of type T. -template -struct IntInterval { - T begin; - T end; - - IntInterval() : begin(-1), end(-1) {} - - IntInterval(T begin, T end) : begin(begin), end(end) {} - - bool operator<(const IntInterval &i) const { - return begin < i.begin || (begin == i.begin && end > i.end); - } - - bool operator==(const IntInterval &i) const { - return begin == i.begin && end == i.end; - } - - bool operator!=(const IntInterval &i) const { - return begin != i.begin || end != i.end; - } - - std::istream &Read(std::istream &strm) { - T n; - ReadType(strm, &n); - begin = n; - ReadType(strm, &n); - end = n; - return strm; - } - - std::ostream &Write(std::ostream &strm) const { - T n = begin; - WriteType(strm, n); - n = end; - WriteType(strm, n); - return strm; - } -}; - -// Stores IntIntervals in a vector. In addition, keeps the count of points in -// all intervals. -template -class VectorIntervalStore { - public: - using Interval = IntInterval; - using Iterator = typename std::vector::const_iterator; - - VectorIntervalStore() : count_(-1) {} - VectorIntervalStore(std::initializer_list intervals_init) - : intervals_(intervals_init), count_(-1) {} - - std::vector *MutableIntervals() { return &intervals_; } - - const Interval *Intervals() const { return intervals_.data(); } - - T Size() const { return intervals_.size(); } - - T Count() const { return count_; } - - void SetCount(T count) { count_ = count; } - - void Clear() { - intervals_.clear(); - count_ = 0; - } - - Iterator begin() const { return intervals_.begin(); } - - Iterator end() const { return intervals_.end(); } - - std::istream &Read(std::istream &strm) { - ReadType(strm, &intervals_); - return ReadType(strm, &count_); - } - - std::ostream &Write(std::ostream &strm) const { - WriteType(strm, intervals_); - return WriteType(strm, count_); - } - - private: - std::vector intervals_; - T count_; -}; - -// Stores and operates on a set of half-open integral intervals [a, b) -// of signed integers of type T. -template > -class IntervalSet { - public: - using Interval = IntInterval; - - IntervalSet(std::initializer_list intervals_init) - : intervals_(intervals_init) {} - - template - explicit IntervalSet(A... args) : intervals_(args...) {} - - // Returns the interval set as a vector. - std::vector *MutableIntervals() { - return intervals_.MutableIntervals(); - } - - // Returns a pointer to an array of Size() elements. - const Interval *Intervals() const { return intervals_.Intervals(); } - - bool Empty() const { return Size() == 0; } - - T Size() const { return intervals_.Size(); } - - // Number of points in the intervals (undefined if not normalized). - T Count() const { return intervals_.Count(); } - - void Clear() { intervals_.Clear(); } - - // Adds an interval set to the set. The result may not be normalized. - void Union(const IntervalSet &iset) { - intervals_.MutableIntervals()->insert(intervals_.MutableIntervals()->end(), - iset.intervals_.begin(), - iset.intervals_.end()); - } - - // Requires intervals be normalized. - bool Member(T value) const { - const Interval interval(value, value); - auto lb = std::lower_bound(intervals_.begin(), intervals_.end(), interval); - if (lb == intervals_.begin()) return false; - return (--lb)->end > value; - } - - // Requires intervals be normalized. - bool operator==(const IntervalSet &iset) const { - return Size() == iset.Size() && - std::equal(intervals_.begin(), intervals_.end(), - iset.intervals_.begin()); - } - - // Requires intervals be normalized. - bool operator!=(const IntervalSet &iset) const { - return Size() != iset.Size() || - !std::equal(intervals_.begin(), intervals_.end(), - iset.intervals_.begin()); - } - - bool Singleton() const { - return Size() == 1 && - intervals_.begin()->begin + 1 == intervals_.begin()->end; - } - - // Sorts, collapses overlapping and adjacent interals, and sets count. - void Normalize(); - - // Intersects an interval set with the set. Requires intervals be normalized. - // The result is normalized. - void Intersect(const IntervalSet &iset, - IntervalSet *oset) const; - - // Complements the set w.r.t [0, maxval). Requires intervals be normalized. - // The result is normalized. - void Complement(T maxval, IntervalSet *oset) const; - - // Subtract an interval set from the set. Requires intervals be normalized. - // The result is normalized. - void Difference(const IntervalSet &iset, - IntervalSet *oset) const; - - // Determines if an interval set overlaps with the set. Requires intervals be - // normalized. - bool Overlaps(const IntervalSet &iset) const; - - // Determines if an interval set overlaps with the set but neither is - // contained in the other. Requires intervals be normalized. - bool StrictlyOverlaps(const IntervalSet &iset) const; - - // Determines if an interval set is contained within the set. Requires - // intervals be normalized. - bool Contains(const IntervalSet &iset) const; - - std::istream &Read(std::istream &strm) { return intervals_.Read(strm); } - - std::ostream &Write(std::ostream &strm) const { - return intervals_.Write(strm); - } - - typename Store::Iterator begin() const { return intervals_.begin(); } - - typename Store::Iterator end() const { return intervals_.end(); } - - private: - Store intervals_; -}; - -// Sorts, collapses overlapping and adjacent intervals, and sets count. -template -void IntervalSet::Normalize() { - auto &intervals = *intervals_.MutableIntervals(); - std::sort(intervals.begin(), intervals.end()); - T count = 0; - T size = 0; - for (T i = 0; i < intervals.size(); ++i) { - auto &inti = intervals[i]; - if (inti.begin == inti.end) continue; - for (T j = i + 1; j < intervals.size(); ++j) { - auto &intj = intervals[j]; - if (intj.begin > inti.end) break; - if (intj.end > inti.end) inti.end = intj.end; - ++i; - } - count += inti.end - inti.begin; - intervals[size++] = inti; - } - intervals.resize(size); - intervals_.SetCount(count); -} - -// Intersects an interval set with the set. Requires intervals be normalized. -// The result is normalized. -template -void IntervalSet::Intersect(const IntervalSet &iset, - IntervalSet *oset) const { - auto *ointervals = oset->MutableIntervals(); - auto it1 = intervals_.begin(); - auto it2 = iset.intervals_.begin(); - ointervals->clear(); - T count = 0; - while (it1 != intervals_.end() && it2 != iset.intervals_.end()) { - if (it1->end <= it2->begin) { - ++it1; - } else if (it2->end <= it1->begin) { - ++it2; - } else { - ointervals->emplace_back(std::max(it1->begin, it2->begin), - std::min(it1->end, it2->end)); - count += ointervals->back().end - ointervals->back().begin; - if (it1->end < it2->end) { - ++it1; - } else { - ++it2; - } - } - } - oset->intervals_.SetCount(count); -} - -// Complements the set w.r.t [0, maxval). Requires intervals be normalized. -// The result is normalized. -template -void IntervalSet::Complement(T maxval, - IntervalSet *oset) const { - auto *ointervals = oset->MutableIntervals(); - ointervals->clear(); - T count = 0; - Interval interval; - interval.begin = 0; - for (const auto current_interval : intervals_) { - interval.end = std::min(current_interval.begin, maxval); - if ((interval.begin) < (interval.end)) { - ointervals->push_back(interval); - count += interval.end - interval.begin; - } - interval.begin = current_interval.end; - } - interval.end = maxval; - if ((interval.begin) < (interval.end)) { - ointervals->push_back(interval); - count += interval.end - interval.begin; - } - oset->intervals_.SetCount(count); -} - -// Subtract an interval set from the set. Requires intervals be normalized. -// The result is normalized. -template -void IntervalSet::Difference(const IntervalSet &iset, - IntervalSet *oset) const { - if (Empty()) { - oset->MutableIntervals()->clear(); - oset->intervals_.SetCount(0); - } else { - IntervalSet cset; - iset.Complement(intervals_.Intervals()[intervals_.Size() - 1].end, &cset); - Intersect(cset, oset); - } -} - -// Determines if an interval set overlaps with the set. Requires intervals be -// normalized. -template -bool IntervalSet::Overlaps(const IntervalSet &iset) const { - auto it1 = intervals_.begin(); - auto it2 = iset.intervals_.begin(); - while (it1 != intervals_.end() && it2 != iset.intervals_.end()) { - if (it1->end <= it2->begin) { - ++it1; - } else if (it2->end <= it1->begin) { - ++it2; - } else { - return true; - } - } - return false; -} - -// Determines if an interval set overlaps with the set but neither is contained -// in the other. Requires intervals be normalized. -template -bool IntervalSet::StrictlyOverlaps( - const IntervalSet &iset) const { - auto it1 = intervals_.begin(); - auto it2 = iset.intervals_.begin(); - bool only1 = false; // Point in intervals_ but not intervals. - bool only2 = false; // Point in intervals but not intervals_. - bool overlap = false; // Point in both intervals_ and intervals. - while (it1 != intervals_.end() && it2 != iset.intervals_.end()) { - if (it1->end <= it2->begin) { // no overlap - it1 first - only1 = true; - ++it1; - } else if (it2->end <= it1->begin) { // no overlap - it2 first - only2 = true; - ++it2; - } else if (it2->begin == it1->begin && it2->end == it1->end) { // equals - overlap = true; - ++it1; - ++it2; - } else if (it2->begin <= it1->begin && it2->end >= it1->end) { // 1 c 2 - only2 = true; - overlap = true; - ++it1; - } else if (it1->begin <= it2->begin && it1->end >= it2->end) { // 2 c 1 - only1 = true; - overlap = true; - ++it2; - } else { // Strict overlap. - only1 = true; - only2 = true; - overlap = true; - } - if (only1 == true && only2 == true && overlap == true) return true; - } - if (it1 != intervals_.end()) only1 = true; - if (it2 != iset.intervals_.end()) only2 = true; - return only1 == true && only2 == true && overlap == true; -} - -// Determines if an interval set is contained within the set. Requires intervals -// be normalized. -template -bool IntervalSet::Contains(const IntervalSet &iset) const { - if (iset.Count() > Count()) return false; - auto it1 = intervals_.begin(); - auto it2 = iset.intervals_.begin(); - while (it1 != intervals_.end() && it2 != iset.intervals_.end()) { - if ((it1->end) <= (it2->begin)) { // No overlap; it1 first. - ++it1; - } else if ((it2->begin) < (it1->begin) || - (it2->end) > (it1->end)) { // No C. - return false; - } else if (it2->end == it1->end) { - ++it1; - ++it2; - } else { - ++it2; - } - } - return it2 == iset.intervals_.end(); -} - -template -std::ostream &operator<<(std::ostream &strm, const IntervalSet &s) { - strm << "{"; - for (T i = 0; i < s.Size(); ++i) { - if (i > 0) { - strm << ","; - } - const auto &interval = s.Intervals()[i]; - strm << "[" << interval.begin << "," << interval.end << ")"; - } - strm << "}"; - return strm; -} - -} // namespace fst - -#endif // FST_INTERVAL_SET_H_ diff --git a/contrib/fstlib/fst/invert.h b/contrib/fstlib/fst/invert.h deleted file mode 100644 index c812022..0000000 --- a/contrib/fstlib/fst/invert.h +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to invert an FST. - -#ifndef FST_INVERT_H_ -#define FST_INVERT_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Mapper to implement inversion of an arc. -template -struct InvertMapper { - using FromArc = A; - using ToArc = A; - - InvertMapper() = default; - - ToArc operator()(const FromArc &arc) const { - return ToArc(arc.olabel, arc.ilabel, arc.weight, arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return MAP_CLEAR_SYMBOLS; - } - - uint64_t Properties(uint64_t props) const { return InvertProperties(props); } -}; - -// Inverts the transduction corresponding to an FST by exchanging the -// FST's input and output labels. -// -// Complexity: -// -// Time: O(V + E) -// Space: O(1) -// -// where V is the number of states and E is the number of arcs. -template -inline void Invert(const Fst &ifst, MutableFst *ofst) { - std::unique_ptr input( - ifst.InputSymbols() ? ifst.InputSymbols()->Copy() : nullptr); - std::unique_ptr output( - ifst.OutputSymbols() ? ifst.OutputSymbols()->Copy() : nullptr); - ArcMap(ifst, ofst, InvertMapper()); - ofst->SetInputSymbols(output.get()); - ofst->SetOutputSymbols(input.get()); -} - -// Destructive variant of the above. -template -inline void Invert(MutableFst *fst) { - std::unique_ptr input( - fst->InputSymbols() ? fst->InputSymbols()->Copy() : nullptr); - std::unique_ptr output( - fst->OutputSymbols() ? fst->OutputSymbols()->Copy() : nullptr); - ArcMap(fst, InvertMapper()); - fst->SetInputSymbols(output.get()); - fst->SetOutputSymbols(input.get()); -} - -// Inverts the transduction corresponding to an FST by exchanging the -// FST's input and output labels. This version is a delayed FST. -// -// Complexity: -// -// Time: O(v + e) -// Space: O(1) -// -// where v is the number of states visited and e is the number of arcs visited. -// Constant time and to visit an input state or arc is assumed and exclusive of -// caching. -template -class InvertFst : public ArcMapFst> { - public: - using Arc = A; - - using Mapper = InvertMapper; - using Impl = internal::ArcMapFstImpl>; - - explicit InvertFst(const Fst &fst) : ArcMapFst(fst) { - GetMutableImpl()->SetOutputSymbols(fst.InputSymbols()); - GetMutableImpl()->SetInputSymbols(fst.OutputSymbols()); - } - - // See Fst<>::Copy() for doc. - InvertFst(const InvertFst &fst, bool safe = false) - : ArcMapFst(fst, safe) {} - - // Get a copy of this InvertFst. See Fst<>::Copy() for further doc. - InvertFst *Copy(bool safe = false) const override { - return new InvertFst(*this, safe); - } - - private: - using ImplToFst::GetMutableImpl; -}; - -// Specialization for InvertFst. -template -class StateIterator> - : public StateIterator>> { - public: - explicit StateIterator(const InvertFst &fst) - : StateIterator>>(fst) {} -}; - -// Specialization for InvertFst. -template -class ArcIterator> - : public ArcIterator>> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const InvertFst &fst, StateId s) - : ArcIterator>>(fst, s) {} -}; - -// Useful alias when using StdArc. -using StdInvertFst = InvertFst; - -} // namespace fst - -#endif // FST_INVERT_H_ diff --git a/contrib/fstlib/fst/isomorphic.h b/contrib/fstlib/fst/isomorphic.h deleted file mode 100644 index d9318b0..0000000 --- a/contrib/fstlib/fst/isomorphic.h +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function to test two FSTs are isomorphic, i.e., they are equal up to a state -// and arc re-ordering. FSTs should be deterministic when viewed as -// unweighted automata. False negatives (but not false positives) are possible -// when the inputs are nondeterministic (when viewed as unweighted automata). - -#ifndef FST_ISOMORPHIC_H_ -#define FST_ISOMORPHIC_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace fst { -namespace internal { - -// Orders weights for equality checking; delta is ignored. -template ::value> * = nullptr> -bool WeightCompare(const Weight &w1, const Weight &w2, float, bool *) { - static const NaturalLess less; - return less(w1, w2); -} - -template ::value> * = nullptr> -bool WeightCompare(const Weight &w1, const Weight &w2, float delta, - bool *error) { - // No natural order; use hash. - const auto q1 = w1.Quantize(delta); - const auto q2 = w2.Quantize(delta); - const auto n1 = q1.Hash(); - const auto n2 = q2.Hash(); - // Hash not unique; very unlikely to happen. - if (n1 == n2 && q1 != q2) { - VLOG(1) << "Isomorphic: Weight hash collision"; - *error = true; - } - return n1 < n2; -} - -template -class Isomorphism { - using StateId = typename Arc::StateId; - - public: - Isomorphism(const Fst &fst1, const Fst &fst2, float delta) - : fst1_(fst1.Copy()), - fst2_(fst2.Copy()), - delta_(delta), - error_(false), - nondet_(false), - comp_(delta, &error_) {} - - // Checks if input FSTs are isomorphic. - bool IsIsomorphic() { - if (fst1_->Start() == kNoStateId && fst2_->Start() == kNoStateId) { - return true; - } - if (fst1_->Start() == kNoStateId || fst2_->Start() == kNoStateId) { - VLOG(1) << "Isomorphic: Only one of the FSTs is empty."; - return false; - } - PairState(fst1_->Start(), fst2_->Start()); - while (!queue_.empty()) { - const auto &[state1, state2] = queue_.front(); - if (!IsIsomorphicState(state1, state2)) { - if (nondet_) { - VLOG(1) << "Isomorphic: Non-determinism as an unweighted automaton. " - << "state1: " << state1 << " state2: " << state2; - error_ = true; - } - return false; - } - queue_.pop(); - } - return true; - } - - bool Error() const { return error_; } - - private: - // Orders arcs for equality checking. - class ArcCompare { - public: - ArcCompare(float delta, bool *error) : delta_(delta), error_(error) {} - - bool operator()(const Arc &arc1, const Arc &arc2) const { - if (arc1.ilabel < arc2.ilabel) return true; - if (arc1.ilabel > arc2.ilabel) return false; - if (arc1.olabel < arc2.olabel) return true; - if (arc1.olabel > arc2.olabel) return false; - if (!ApproxEqual(arc1.weight, arc2.weight, delta_)) { - return WeightCompare(arc1.weight, arc2.weight, delta_, error_); - } else { - return arc1.nextstate < arc2.nextstate; - } - } - - private: - const float delta_; - bool *error_; - }; - - // Maintains state correspondences and queue. - bool PairState(StateId s1, StateId s2) { - if (state_pairs_.size() <= s1) state_pairs_.resize(s1 + 1, kNoStateId); - if (state_pairs_[s1] == s2) { - return true; // Already seen this pair. - } else if (state_pairs_[s1] != kNoStateId) { - return false; // s1 already paired with another s2. - } - VLOG(3) << "Pairing states: (" << s1 << ", " << s2 << ")"; - state_pairs_[s1] = s2; - queue_.emplace(s1, s2); - return true; - } - - // Checks if state pair is isomorphic. - bool IsIsomorphicState(StateId s1, StateId s2); - - std::unique_ptr> fst1_; - std::unique_ptr> fst2_; - float delta_; // Weight equality delta. - std::vector arcs1_; // For sorting arcs on FST1. - std::vector arcs2_; // For sorting arcs on FST2. - std::vector state_pairs_; // Maintains state correspondences. - std::queue> queue_; // Queue of state pairs. - bool error_; // Error flag. - bool nondet_; // Nondeterminism detected. - ArcCompare comp_; -}; - -template -bool Isomorphism::IsIsomorphicState(StateId s1, StateId s2) { - if (!ApproxEqual(fst1_->Final(s1), fst2_->Final(s2), delta_)) { - VLOG(1) << "Isomorphic: Final weights not equal to within delta=" << delta_ - << ": " - << "fst1.Final(" << s1 << ") = " << fst1_->Final(s1) << ", " - << "fst2.Final(" << s2 << ") = " << fst2_->Final(s2); - return false; - } - const auto narcs1 = fst1_->NumArcs(s1); - const auto narcs2 = fst2_->NumArcs(s2); - if (narcs1 != narcs2) { - VLOG(1) << "Isomorphic: NumArcs not equal. " - << "fst1.NumArcs(" << s1 << ") = " << narcs1 << ", " - << "fst2.NumArcs(" << s2 << ") = " << narcs2; - return false; - } - ArcIterator> aiter1(*fst1_, s1); - ArcIterator> aiter2(*fst2_, s2); - arcs1_.clear(); - arcs1_.reserve(narcs1); - arcs2_.clear(); - arcs2_.reserve(narcs2); - for (; !aiter1.Done(); aiter1.Next(), aiter2.Next()) { - arcs1_.push_back(aiter1.Value()); - arcs2_.push_back(aiter2.Value()); - } - std::sort(arcs1_.begin(), arcs1_.end(), comp_); - std::sort(arcs2_.begin(), arcs2_.end(), comp_); - for (size_t i = 0; i < arcs1_.size(); ++i) { - const auto &arc1 = arcs1_[i]; - const auto &arc2 = arcs2_[i]; - if (arc1.ilabel != arc2.ilabel) { - VLOG(1) << "Isomorphic: ilabels not equal. " - << "state1: " << s1 << " arc1: *" << arc1.ilabel << "* " - << arc1.olabel << " " << arc1.weight << " " << arc1.nextstate - << " state2: " << s2 << " arc2: *" << arc2.ilabel << "* " - << arc2.olabel << " " << arc2.weight << " " << arc2.nextstate; - return false; - } - if (arc1.olabel != arc2.olabel) { - VLOG(1) << "Isomorphic: olabels not equal. " - << "state1: " << s1 << " arc1: " << arc1.ilabel << " *" - << arc1.olabel << "* " << arc1.weight << " " << arc1.nextstate - << " state2: " << s2 << " arc2: " << arc2.ilabel << " *" - << arc2.olabel << "* " << arc2.weight << " " << arc2.nextstate; - return false; - } - if (!ApproxEqual(arc1.weight, arc2.weight, delta_)) { - VLOG(1) << "Isomorphic: weights not ApproxEqual. " - << "state1: " << s1 << " arc1: " << arc1.ilabel << " " - << arc1.olabel << " *" << arc1.weight << "* " << arc1.nextstate - << " state2: " << s2 << " arc2: " << arc2.ilabel << " " - << arc2.olabel << " *" << arc2.weight << "* " << arc2.nextstate; - return false; - } - if (!PairState(arc1.nextstate, arc2.nextstate)) { - VLOG(1) << "Isomorphic: nextstates could not be paired. " - << "state1: " << s1 << " arc1: " << arc1.ilabel << " " - << arc1.olabel << " " << arc1.weight << " *" << arc1.nextstate - << "* " - << "state2: " << s2 << " arc2: " << arc2.ilabel << " " - << arc2.olabel << " " << arc2.weight << " *" << arc2.nextstate - << "*"; - return false; - } - if (i > 0) { // Checks for non-determinism. - const auto &arc0 = arcs1_[i - 1]; - if (arc1.ilabel == arc0.ilabel && arc1.olabel == arc0.olabel && - ApproxEqual(arc1.weight, arc0.weight, delta_)) { - // Any subsequent matching failure maybe a false negative - // since we only consider one permutation when pairing destination - // states of nondeterministic transitions. - VLOG(1) << "Isomorphic: Detected non-determinism as an unweighted " - << "automaton; deferring error. " - << "state: " << s1 << " arc1: " << arc1.ilabel << " " - << arc1.olabel << " " << arc1.weight << " " << arc1.nextstate - << " arc2: " << arc2.ilabel << " " << arc2.olabel << " " - << arc2.weight << " " << arc2.nextstate; - nondet_ = true; - } - } - } - return true; -} - -} // namespace internal - -// Tests if two FSTs have the same states and arcs up to a reordering. -// Inputs should be deterministic when viewed as unweighted automata. -// When the inputs are nondeterministic, the algorithm only considers one -// permutation for each set of equivalent nondeterministic transitions -// (the permutation that preserves state ID ordering) and hence might return -// false negatives (but it never returns false positives). -template -bool Isomorphic(const Fst &fst1, const Fst &fst2, - float delta = kDelta) { - internal::Isomorphism iso(fst1, fst2, delta); - const bool result = iso.IsIsomorphic(); - if (iso.Error()) { - FSTERROR() << "Isomorphic: Cannot determine if inputs are isomorphic"; - return false; - } else { - return result; - } -} - -} // namespace fst - -#endif // FST_ISOMORPHIC_H_ diff --git a/contrib/fstlib/fst/label-reachable.h b/contrib/fstlib/fst/label-reachable.h deleted file mode 100644 index d66fbfa..0000000 --- a/contrib/fstlib/fst/label-reachable.h +++ /dev/null @@ -1,612 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to determine if a non-epsilon label can be read as the first -// non-epsilon symbol along some path from a given state. - -#ifndef FST_LABEL_REACHABLE_H_ -#define FST_LABEL_REACHABLE_H_ - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Stores shareable data for label reachable class copies. -template -class LabelReachableData { - public: - using LabelIntervalSet = IntervalSet { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - virtual MutableFst &operator=(const Fst &fst) = 0; - - MutableFst &operator=(const MutableFst &fst) { - return operator=(static_cast &>(fst)); - } - - // Sets the initial state. - virtual void SetStart(StateId) = 0; - - // Sets a state's final weight. - virtual void SetFinal(StateId s, Weight weight = Weight::One()) = 0; - - // Sets property bits w.r.t. mask. - virtual void SetProperties(uint64_t props, uint64_t mask) = 0; - - // Adds a state and returns its ID. - virtual StateId AddState() = 0; - - // Adds multiple states. - virtual void AddStates(size_t) = 0; - - // Adds an arc to state. - virtual void AddArc(StateId, const Arc &) = 0; - - // Adds an arc (passed by rvalue reference) to state. Allows subclasses - // to optionally implement move semantics. Defaults to lvalue overload. - virtual void AddArc(StateId state, Arc &&arc) { AddArc(state, arc); } - - // Deletes some states, preserving original StateId ordering. - virtual void DeleteStates(const std::vector &) = 0; - - // Delete all states. - virtual void DeleteStates() = 0; - - // Delete some arcs at a given state. - virtual void DeleteArcs(StateId, size_t) = 0; - - // Delete all arcs at a given state. - virtual void DeleteArcs(StateId) = 0; - - // Optional, best effort only. - virtual void ReserveStates(size_t) {} - - // Optional, best effort only. - virtual void ReserveArcs(StateId, size_t) {} - - // Returns input label symbol table or nullptr if not specified. - const SymbolTable *InputSymbols() const override = 0; - - // Returns output label symbol table or nullptr if not specified. - const SymbolTable *OutputSymbols() const override = 0; - - // Returns input label symbol table or nullptr if not specified. - virtual SymbolTable *MutableInputSymbols() = 0; - - // Returns output label symbol table or nullptr if not specified. - virtual SymbolTable *MutableOutputSymbols() = 0; - - // Sets input label symbol table; pass nullptr to delete table. - virtual void SetInputSymbols(const SymbolTable *isyms) = 0; - - // Sets output label symbol table; pass nullptr to delete table. - virtual void SetOutputSymbols(const SymbolTable *osyms) = 0; - - // Gets a copy of this MutableFst. See Fst<>::Copy() for further doc. - MutableFst *Copy(bool safe = false) const override = 0; - - // Reads a MutableFst from an input stream, returning nullptr on error. - static MutableFst *Read(std::istream &strm, const FstReadOptions &opts) { - FstReadOptions ropts(opts); - FstHeader hdr; - if (ropts.header) { - hdr = *opts.header; - } else { - if (!hdr.Read(strm, opts.source)) return nullptr; - ropts.header = &hdr; - } - if (!(hdr.Properties() & kMutable)) { - LOG(ERROR) << "MutableFst::Read: Not a MutableFst: " << ropts.source; - return nullptr; - } - const auto &fst_type = hdr.FstType(); - const auto reader = FstRegister::GetRegister()->GetReader(fst_type); - if (!reader) { - LOG(ERROR) << "MutableFst::Read: Unknown FST type \"" << fst_type - << "\" (arc type = \"" << A::Type() << "\"): " << ropts.source; - return nullptr; - } - auto *fst = reader(strm, ropts); - if (!fst) return nullptr; - return down_cast(fst); - } - - // Reads a MutableFst from a file; returns nullptr on error. An empty - // source results in reading from standard input. If convert is true, - // convert to a mutable FST subclass (given by convert_type) in the case - // that the input FST is non-mutable. - static MutableFst *Read(const std::string &source, bool convert = false, - std::string_view convert_type = "vector") { - if (convert == false) { - if (!source.empty()) { - std::ifstream strm(source, - std::ios_base::in | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "MutableFst::Read: Can't open file: " << source; - return nullptr; - } - return Read(strm, FstReadOptions(source)); - } else { - return Read(std::cin, FstReadOptions("standard input")); - } - } else { // Converts to 'convert_type' if not mutable. - std::unique_ptr> ifst(Fst::Read(source)); - if (!ifst) return nullptr; - if (ifst->Properties(kMutable, false)) { - return down_cast(ifst.release()); - } else { - std::unique_ptr> ofst(Convert(*ifst, convert_type)); - ifst.reset(); - if (!ofst) return nullptr; - if (!ofst->Properties(kMutable, false)) { - LOG(ERROR) << "MutableFst: Bad convert type: " << convert_type; - } - return down_cast(ofst.release()); - } - } - } - - // For generic mutuble arc iterator construction; not normally called - // directly by users. - virtual void InitMutableArcIterator(StateId s, - MutableArcIteratorData *data) = 0; -}; - -// Mutable arc iterator interface, templated on the Arc definition. This is -// used by mutable arc iterator specializations that are returned by the -// InitMutableArcIterator MutableFst method. -template -class MutableArcIteratorBase : public ArcIteratorBase { - public: - // Sets current arc. - virtual void SetValue(const Arc &) = 0; -}; - -template -struct MutableArcIteratorData { - std::unique_ptr> base; // Specific iterator. -}; - -// Generic mutable arc iterator, templated on the FST definition; a wrapper -// around a pointer to a more specific one. -// -// Here is a typical use: -// -// for (MutableArcIterator aiter(&fst, s); -// !aiter.Done(); -// aiter.Next()) { -// StdArc arc = aiter.Value(); -// arc.ilabel = 7; -// aiter.SetValue(arc); -// ... -// } -// -// This version requires function calls. -template -class MutableArcIterator { - public: - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - - MutableArcIterator(FST *fst, StateId s) { - fst->InitMutableArcIterator(s, &data_); - } - - bool Done() const { return data_.base->Done(); } - - const Arc &Value() const { return data_.base->Value(); } - - void Next() { data_.base->Next(); } - - size_t Position() const { return data_.base->Position(); } - - void Reset() { data_.base->Reset(); } - - void Seek(size_t a) { data_.base->Seek(a); } - - void SetValue(const Arc &arc) { data_.base->SetValue(arc); } - - uint8_t Flags() const { return data_.base->Flags(); } - - void SetFlags(uint8_t flags, uint8_t mask) { - return data_.base->SetFlags(flags, mask); - } - - private: - MutableArcIteratorData data_; - - MutableArcIterator(const MutableArcIterator &) = delete; - MutableArcIterator &operator=(const MutableArcIterator &) = delete; -}; - -namespace internal { - -// MutableFst case: abstract methods. -template -inline typename Arc::Weight Final(const MutableFst &fst, - typename Arc::StateId s) { - return fst.Final(s); -} - -template -inline ssize_t NumArcs(const MutableFst &fst, typename Arc::StateId s) { - return fst.NumArcs(s); -} - -template -inline ssize_t NumInputEpsilons(const MutableFst &fst, - typename Arc::StateId s) { - return fst.NumInputEpsilons(s); -} - -template -inline ssize_t NumOutputEpsilons(const MutableFst &fst, - typename Arc::StateId s) { - return fst.NumOutputEpsilons(s); -} - -} // namespace internal - -// A useful alias when using StdArc. -using StdMutableFst = MutableFst; - -// This is a helper class template useful for attaching a MutableFst interface -// to its implementation, handling reference counting and COW semantics. -template > -class ImplToMutableFst : public ImplToExpandedFst { - public: - using Arc = typename Impl::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using ImplToExpandedFst::operator=; - - void SetStart(StateId s) override { - MutateCheck(); - GetMutableImpl()->SetStart(s); - } - - void SetFinal(StateId s, Weight weight = Weight::One()) override { - MutateCheck(); - GetMutableImpl()->SetFinal(s, std::move(weight)); - } - - void SetProperties(uint64_t props, uint64_t mask) override { - // Can skip mutate check if extrinsic properties don't change, - // since it is then safe to update all (shallow) copies - const auto exprops = kExtrinsicProperties & mask; - if (GetImpl()->Properties(exprops) != (props & exprops)) MutateCheck(); - GetMutableImpl()->SetProperties(props, mask); - } - - StateId AddState() override { - MutateCheck(); - return GetMutableImpl()->AddState(); - } - - void AddStates(size_t n) override { - MutateCheck(); - return GetMutableImpl()->AddStates(n); - } - - void AddArc(StateId s, const Arc &arc) override { - MutateCheck(); - GetMutableImpl()->AddArc(s, arc); - } - - void AddArc(StateId s, Arc &&arc) override { - MutateCheck(); - GetMutableImpl()->AddArc(s, std::forward(arc)); - } - - void DeleteStates(const std::vector &dstates) override { - MutateCheck(); - GetMutableImpl()->DeleteStates(dstates); - } - - void DeleteStates() override { - if (!Unique()) { - const auto *isymbols = GetImpl()->InputSymbols(); - const auto *osymbols = GetImpl()->OutputSymbols(); - SetImpl(std::make_shared()); - GetMutableImpl()->SetInputSymbols(isymbols); - GetMutableImpl()->SetOutputSymbols(osymbols); - } else { - GetMutableImpl()->DeleteStates(); - } - } - - void DeleteArcs(StateId s, size_t n) override { - MutateCheck(); - GetMutableImpl()->DeleteArcs(s, n); - } - - void DeleteArcs(StateId s) override { - MutateCheck(); - GetMutableImpl()->DeleteArcs(s); - } - - void ReserveStates(size_t n) override { - MutateCheck(); - GetMutableImpl()->ReserveStates(n); - } - - void ReserveArcs(StateId s, size_t n) override { - MutateCheck(); - GetMutableImpl()->ReserveArcs(s, n); - } - - const SymbolTable *InputSymbols() const override { - return GetImpl()->InputSymbols(); - } - - const SymbolTable *OutputSymbols() const override { - return GetImpl()->OutputSymbols(); - } - - SymbolTable *MutableInputSymbols() override { - MutateCheck(); - return GetMutableImpl()->InputSymbols(); - } - - SymbolTable *MutableOutputSymbols() override { - MutateCheck(); - return GetMutableImpl()->OutputSymbols(); - } - - void SetInputSymbols(const SymbolTable *isyms) override { - MutateCheck(); - GetMutableImpl()->SetInputSymbols(isyms); - } - - void SetOutputSymbols(const SymbolTable *osyms) override { - MutateCheck(); - GetMutableImpl()->SetOutputSymbols(osyms); - } - - protected: - using ImplToExpandedFst::GetImpl; - using ImplToExpandedFst::GetMutableImpl; - using ImplToExpandedFst::Unique; - using ImplToExpandedFst::SetImpl; - using ImplToExpandedFst::InputSymbols; - - explicit ImplToMutableFst(std::shared_ptr impl) - : ImplToExpandedFst(impl) {} - - ImplToMutableFst(const ImplToMutableFst &fst, bool safe) - : ImplToExpandedFst(fst, safe) {} - - void MutateCheck() { - if (!Unique()) SetImpl(std::make_shared(*this)); - } -}; - -} // namespace fst - -#endif // FST_MUTABLE_FST_H_ diff --git a/contrib/fstlib/fst/pair-weight.h b/contrib/fstlib/fst/pair-weight.h deleted file mode 100644 index 563d469..0000000 --- a/contrib/fstlib/fst/pair-weight.h +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Pair weight templated base class for weight classes that contain two weights -// (e.g. Product, Lexicographic). - -#ifndef FST_PAIR_WEIGHT_H_ -#define FST_PAIR_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace fst { - -template -class PairWeight { - public: - using ReverseWeight = - PairWeight; - - PairWeight() = default; - - PairWeight(W1 w1, W2 w2) : value1_(std::move(w1)), value2_(std::move(w2)) {} - - static const PairWeight &Zero() { - static const PairWeight zero(W1::Zero(), W2::Zero()); - return zero; - } - - static const PairWeight &One() { - static const PairWeight one(W1::One(), W2::One()); - return one; - } - - static const PairWeight &NoWeight() { - static const PairWeight no_weight(W1::NoWeight(), W2::NoWeight()); - return no_weight; - } - - std::istream &Read(std::istream &strm) { - value1_.Read(strm); - return value2_.Read(strm); - } - - std::ostream &Write(std::ostream &strm) const { - value1_.Write(strm); - return value2_.Write(strm); - } - - bool Member() const { return value1_.Member() && value2_.Member(); } - - size_t Hash() const { - const auto h1 = value1_.Hash(); - const auto h2 = value2_.Hash(); - static constexpr int lshift = 5; - static constexpr int rshift = CHAR_BIT * sizeof(size_t) - 5; - return h1 << lshift ^ h1 >> rshift ^ h2; - } - - PairWeight Quantize(float delta = kDelta) const { - return PairWeight(value1_.Quantize(delta), value2_.Quantize(delta)); - } - - ReverseWeight Reverse() const { - return ReverseWeight(value1_.Reverse(), value2_.Reverse()); - } - - const W1 &Value1() const { return value1_; } - - const W2 &Value2() const { return value2_; } - - void SetValue1(const W1 &weight) { value1_ = weight; } - - void SetValue2(const W2 &weight) { value2_ = weight; } - - private: - W1 value1_; - W2 value2_; -}; - -template -inline bool operator==(const PairWeight &w1, - const PairWeight &w2) { - return w1.Value1() == w2.Value1() && w1.Value2() == w2.Value2(); -} - -template -inline bool operator!=(const PairWeight &w1, - const PairWeight &w2) { - return w1.Value1() != w2.Value1() || w1.Value2() != w2.Value2(); -} - -template -inline bool ApproxEqual(const PairWeight &w1, - const PairWeight &w2, float delta = kDelta) { - return ApproxEqual(w1.Value1(), w2.Value1(), delta) && - ApproxEqual(w1.Value2(), w2.Value2(), delta); -} - -template -inline std::ostream &operator<<(std::ostream &strm, - const PairWeight &weight) { - CompositeWeightWriter writer(strm); - writer.WriteBegin(); - writer.WriteElement(weight.Value1()); - writer.WriteElement(weight.Value2()); - writer.WriteEnd(); - return strm; -} - -template -inline std::istream &operator>>(std::istream &strm, - PairWeight &weight) { - CompositeWeightReader reader(strm); - reader.ReadBegin(); - W1 w1; - reader.ReadElement(&w1); - weight.SetValue1(w1); - W2 w2; - reader.ReadElement(&w2, true); - weight.SetValue2(w2); - reader.ReadEnd(); - return strm; -} - -// This function object returns weights by calling the underlying generators -// and forming a pair. This is intended primarily for testing. -template -class WeightGenerate> { - public: - using Weight = PairWeight; - using Generate1 = WeightGenerate; - using Generate2 = WeightGenerate; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true) - : generate1_(seed, allow_zero), generate2_(seed, allow_zero) {} - - Weight operator()() const { return Weight(generate1_(), generate2_()); } - - private: - const Generate1 generate1_; - const Generate2 generate2_; -}; - -} // namespace fst - -#endif // FST_PAIR_WEIGHT_H_ diff --git a/contrib/fstlib/fst/partition.h b/contrib/fstlib/fst/partition.h deleted file mode 100644 index efa89f3..0000000 --- a/contrib/fstlib/fst/partition.h +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to create a partition of states. - -#ifndef FST_PARTITION_H_ -#define FST_PARTITION_H_ - -#include -#include -#include -#include - -#include - -namespace fst { -namespace internal { - -template -class PartitionIterator; - -// Defines a partitioning of elements, used to represent equivalence classes -// for FST operations like minimization. T must be a signed integer type. -// -// The elements are numbered from 0 to num_elements - 1. -// Initialize(num_elements) sets up the class for a given number of elements. -// We maintain a partition of these elements into classes. The classes are also -// numbered from zero; you can add a class with AddClass(), or add them in bulk -// with AllocateClasses(num_classes). Initially the elements are not assigned -// to any class; you set up the initial mapping from elements to classes by -// calling Add(element_id, class_id). You can also move an element to a -// different class by calling Move(element_id, class_id). -// -// We also support a rather specialized interface that allows you to efficiently -// split classes in the Hopcroft minimization algorithm. This maintains a -// binary partition of each class. Let's call these, rather arbitrarily, the -// 'yes' subset and the 'no' subset of each class, and assume that by default, -// each element of a class is in its 'no' subset. When one calls -// SplitOn(element_id), element_id is moved to the 'yes' subset of its class. -// (If it was already in the 'yes' set, it just stays there). The aim is to -// enable (later) splitting the class in two in time no greater than the time -// already spent calling SplitOn() for that class. We keep a list of the classes -// which have nonempty 'yes' sets, as visited_classes_. When one calls -// FinalizeSplit(Queue *l), for each class in visited_classes_ whose 'yes' -// and 'no' sets are both nonempty, it will create a new class consisting of -// the smaller of the two subsets (and this class will be added to the queue), -// and the old class will now be the larger of the two subsets. This call also -// resets all the yes/no partitions so that everything is in the 'no' subsets. -// -// One cannot use the Move() function if SplitOn() has been called without -// a subsequent call to FinalizeSplit() -template -class Partition { - static_assert(std::is_signed_v && std::is_integral_v, - "T must be a signed integer type"); - - public: - Partition() = default; - - explicit Partition(T num_elements) { Initialize(num_elements); } - - // Creates an empty partition for num_elements. This means that the elements - // are not assigned to a class (i.e class_index = -1); you should set up the - // number of classes using AllocateClasses() or AddClass(), and allocate each - // element to a class by calling Add(element, class_id). - void Initialize(size_t num_elements) { - elements_.resize(num_elements); - classes_.reserve(num_elements); - classes_.clear(); - yes_counter_ = 1; - } - - // Adds a class; returns new number of classes. - T AddClass() { - auto num_classes = classes_.size(); - classes_.resize(num_classes + 1); - return num_classes; - } - - // Adds 'num_classes' new (empty) classes. - void AllocateClasses(T num_classes) { - classes_.resize(classes_.size() + num_classes); - } - - // Adds element_id to class_id. element_id should already have been allocated - // by calling Initialize(num_elements)---or the constructor taking - // num_elements---with num_elements > element_id. element_id must not - // currently be a member of any class; once elements have been added to a - // class, use the Move() method to move them from one class to another. - void Add(T element_id, T class_id) { - auto &this_element = elements_[element_id]; - auto &this_class = classes_[class_id]; - ++this_class.size; - // Adds the element to the 'no' subset of the class. - auto no_head = this_class.no_head; - if (no_head >= 0) elements_[no_head].prev_element = element_id; - this_class.no_head = element_id; - this_element.class_id = class_id; - // Adds to the 'no' subset of the class. - this_element.yes = 0; - this_element.next_element = no_head; - this_element.prev_element = -1; - } - - // Moves element_id from 'no' subset of its current class to 'no' subset of - // class class_id. This may not work correctly if you have called SplitOn() - // [for any element] and haven't subsequently called FinalizeSplit(). - void Move(T element_id, T class_id) { - auto elements = &(elements_[0]); - auto &element = elements[element_id]; - auto &old_class = classes_[element.class_id]; - --old_class.size; - // Excises the element from the 'no' list of its old class, where it is - // assumed to be. - if (element.prev_element >= 0) { - elements[element.prev_element].next_element = element.next_element; - } else { - old_class.no_head = element.next_element; - } - if (element.next_element >= 0) { - elements[element.next_element].prev_element = element.prev_element; - } - // Adds to new class. - Add(element_id, class_id); - } - - // Moves element_id to the 'yes' subset of its class if it was in the 'no' - // subset, and marks the class as having been visited. - void SplitOn(T element_id) { - auto elements = &(elements_[0]); - auto &element = elements[element_id]; - if (element.yes == yes_counter_) { - return; // Already in the 'yes' set; nothing to do. - } - auto class_id = element.class_id; - auto &this_class = classes_[class_id]; - // Excises the element from the 'no' list of its class. - if (element.prev_element >= 0) { - elements[element.prev_element].next_element = element.next_element; - } else { - this_class.no_head = element.next_element; - } - if (element.next_element >= 0) { - elements[element.next_element].prev_element = element.prev_element; - } - // Adds the element to the 'yes' list. - if (this_class.yes_head >= 0) { - elements[this_class.yes_head].prev_element = element_id; - } else { - visited_classes_.push_back(class_id); - } - element.yes = yes_counter_; - element.next_element = this_class.yes_head; - element.prev_element = -1; - this_class.yes_head = element_id; - this_class.yes_size++; - } - - // This should be called after one has possibly called SplitOn for one or more - // elements, thus moving those elements to the 'yes' subset for their class. - // For each class that has a nontrivial split (i.e., it's not the case that - // all members are in the 'yes' or 'no' subset), this function creates a new - // class containing the smaller of the two subsets of elements, leaving the - // larger group of elements in the old class. The identifier of the new class - // will be added to the queue provided as the pointer L. This method then - // moves all elements to the 'no' subset of their class. - template - void FinalizeSplit(Queue *queue) { - for (const auto &visited_class : visited_classes_) { - const auto new_class = SplitRefine(visited_class); - if (new_class != -1 && queue) queue->Enqueue(new_class); - } - visited_classes_.clear(); - // Incrementation sets all the 'yes' members of the elements to false. - ++yes_counter_; - } - - const T ClassId(T element_id) const { return elements_[element_id].class_id; } - - const size_t ClassSize(T class_id) const { return classes_[class_id].size; } - - const T NumClasses() const { return classes_.size(); } - - private: - friend class PartitionIterator; - - // Information about a given element. - struct Element { - T class_id; // Class ID of this element. - T yes; // This is to be interpreted as a bool, true if it's in the - // 'yes' set of this class. The interpretation as bool is - // (yes == yes_counter_ ? true : false). - T next_element; // Next element in the 'no' list or 'yes' list of this - // class, whichever of the two we belong to (think of - // this as the 'next' in a doubly-linked list, although - // it is an index into the elements array). Negative - // values corresponds to null. - T prev_element; // Previous element in the 'no' or 'yes' doubly linked - // list. Negative values corresponds to null. - }; - - // Information about a given class. - struct Class { - Class() : size(0), yes_size(0), no_head(-1), yes_head(-1) {} - T size; // Total number of elements in this class ('no' plus 'yes' - // subsets). - T yes_size; // Total number of elements of 'yes' subset of this class. - T no_head; // Index of head element of doubly-linked list in 'no' subset. - // Everything is in the 'no' subset until you call SplitOn(). - // -1 means no element. - T yes_head; // Index of head element of doubly-linked list in 'yes' subset. - // -1 means no element. - }; - - // This method, called from FinalizeSplit(), checks whether a class has to - // be split (a class will be split only if its 'yes' and 'no' subsets are - // both nonempty, but one can assume that since this function was called, the - // 'yes' subset is nonempty). It splits by taking the smaller subset and - // making it a new class, and leaving the larger subset of elements in the - // 'no' subset of the old class. It returns the new class if created, or -1 - // if none was created. - T SplitRefine(T class_id) { - auto yes_size = classes_[class_id].yes_size; - auto size = classes_[class_id].size; - auto no_size = size - yes_size; - if (no_size == 0) { - // All members are in the 'yes' subset, so we don't have to create a new - // class, just move them all to the 'no' subset. - classes_[class_id].no_head = classes_[class_id].yes_head; - classes_[class_id].yes_head = -1; - classes_[class_id].yes_size = 0; - return -1; - } else { - auto new_class_id = classes_.size(); - classes_.resize(classes_.size() + 1); - auto &old_class = classes_[class_id]; - auto &new_class = classes_[new_class_id]; - // The new_class will have the values from the constructor. - if (no_size < yes_size) { - // Moves the 'no' subset to new class ('no' subset). - new_class.no_head = old_class.no_head; - new_class.size = no_size; - // And makes the 'yes' subset of the old class ('no' subset). - old_class.no_head = old_class.yes_head; - old_class.yes_head = -1; - old_class.size = yes_size; - old_class.yes_size = 0; - } else { - // Moves the 'yes' subset to the new class (to the 'no' subset) - new_class.size = yes_size; - new_class.no_head = old_class.yes_head; - // Retains only the 'no' subset in the old class. - old_class.size = no_size; - old_class.yes_size = 0; - old_class.yes_head = -1; - } - auto elements = &(elements_[0]); - // Updates the 'class_id' of all the elements we moved. - for (auto e = new_class.no_head; e >= 0; e = elements[e].next_element) { - elements[e].class_id = new_class_id; - } - return new_class_id; - } - } - - // elements_[i] contains all info about the i'th element. - std::vector elements_; - // classes_[i] contains all info about the i'th class. - std::vector classes_; - // Set of visited classes to be used in split refine. - std::vector visited_classes_; - // yes_counter_ is used in interpreting the 'yes' members of class Element. - // If element.yes == yes_counter_, we interpret that element as being in the - // 'yes' subset of its class. This allows us to, in effect, set all those - // bools to false at a stroke by incrementing yes_counter_. - T yes_counter_; -}; - -// Iterates over members of the 'no' subset of a class in a partition. (When -// this is used, everything is in the 'no' subset). -template -class PartitionIterator { - public: - using Element = typename Partition::Element; - - PartitionIterator(const Partition &partition, T class_id) - : partition_(partition), - element_id_(partition_.classes_[class_id].no_head), - class_id_(class_id) {} - - bool Done() { return element_id_ < 0; } - - const T Value() { return element_id_; } - - void Next() { element_id_ = partition_.elements_[element_id_].next_element; } - - void Reset() { element_id_ = partition_.classes_[class_id_].no_head; } - - private: - const Partition &partition_; - T element_id_; - T class_id_; -}; - -} // namespace internal -} // namespace fst - -#endif // FST_PARTITION_H_ diff --git a/contrib/fstlib/fst/power-weight-mappers.h b/contrib/fstlib/fst/power-weight-mappers.h deleted file mode 100644 index fc64238..0000000 --- a/contrib/fstlib/fst/power-weight-mappers.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Conversions to/from PowerWeight and SparsePowerWeight. - -#ifndef FST_POWER_WEIGHT_MAPPERS_H_ -#define FST_POWER_WEIGHT_MAPPERS_H_ - -namespace fst { - -// Converts FromWeight to ToPowerWeight (with one component). -// ToPowerWeight may be PowerWeight or SparsePowerWeight. -template -class ToPowerWeightMapper { - public: - using FromWeight = FromWeight_; - using ToWeight = ToPowerWeight; - using Index = typename ToPowerWeight::Index; - - explicit ToPowerWeightMapper(Index index = 0) : index_(index) {} - - ToPowerWeight operator()(const FromWeight &w) const { - return ToPowerWeight(index_, w.Value()); - } - - private: - const Index index_; -}; - -// Converts FromPowerWeight to ToWeight. Uses only one component. -// FromPowerWeight may be PowerWeight or SparsePowerWeight. -template -class FromPowerWeightMapper { - public: - using FromWeight = FromPowerWeight; - using ToWeight = ToWeight_; - using Index = typename FromPowerWeight::Index; - - explicit FromPowerWeightMapper(Index index = 0) : index_(index) {} - - ToWeight operator()(const FromPowerWeight &w) const { - return ToWeight(w.Value(index_)); - } - - private: - const Index index_; -}; - -// Projects to one dimension of the weight vector, filling the indices -// with `default_weight`. -// PowerWeightT may be PowerWeight or SparsePowerWeight. -template -class ProjectPowerWeightMapper { - public: - using FromWeight = PowerWeightT; - using ToWeight = PowerWeightT; - using Index = typename PowerWeightT::Index; - using ComponentWeight = typename PowerWeightT::Weight; - - explicit ProjectPowerWeightMapper( - Index from_index = 0, Index to_index = 0, - const ComponentWeight &default_weight = ComponentWeight::Zero()) - : from_index_(from_index), - to_index_(to_index), - default_weight_(default_weight) {} - - PowerWeightT operator()(const PowerWeightT &w) const { - return PowerWeightT(to_index_, w.Value(from_index_), default_weight_); - } - - private: - const Index from_index_; - const Index to_index_; - const ComponentWeight default_weight_; -}; - -// Applies a transformation function to each weight vector. -// PowerWeightT may be PowerWeight or SparsePowerWeight. -template -class TransformPowerWeightMapper { - public: - using TransformFn = TransformFn_; - using FromWeight = PowerWeightT; - using ToWeight = PowerWeightT; - - explicit TransformPowerWeightMapper( - const TransformFn &transform = TransformFn()) - : transform_(transform) {} - - PowerWeightT operator()(const PowerWeightT &w) const { return transform_(w); } - - private: - TransformFn transform_; -}; - -} // namespace fst - -#endif // FST_POWER_WEIGHT_MAPPERS_H_ diff --git a/contrib/fstlib/fst/power-weight.h b/contrib/fstlib/fst/power-weight.h deleted file mode 100644 index c148001..0000000 --- a/contrib/fstlib/fst/power-weight.h +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Cartesian power weight semiring operation definitions. - -#ifndef FST_POWER_WEIGHT_H_ -#define FST_POWER_WEIGHT_H_ - -#include -#include -#include -#include - -#include -#include - -namespace fst { - -// Cartesian power semiring: W ^ n -// -// Forms: -// - a left semimodule when W is a left semiring, -// - a right semimodule when W is a right semiring, -// - a bisemimodule when W is a semiring, -// the free semimodule of rank n over W -// The Times operation is overloaded to provide the left and right scalar -// products. -template -class PowerWeight : public TupleWeight { - public: - using ReverseWeight = PowerWeight; - - PowerWeight() = default; - - explicit PowerWeight(const TupleWeight &weight) - : TupleWeight(weight) {} - - template - PowerWeight(Iterator begin, Iterator end) : TupleWeight(begin, end) {} - - // Initialize component `index` to `weight`; initialize all other components - // to `default_weight` - PowerWeight(size_t index, const W &weight, - const W &default_weight = W::Zero()) - : TupleWeight(index, weight, default_weight) {} - - static const PowerWeight &Zero() { - static const PowerWeight zero(TupleWeight::Zero()); - return zero; - } - - static const PowerWeight &One() { - static const PowerWeight one(TupleWeight::One()); - return one; - } - - static const PowerWeight &NoWeight() { - static const PowerWeight no_weight(TupleWeight::NoWeight()); - return no_weight; - } - - static const std::string &Type() { - static const std::string *const type = - new std::string(W::Type() + "_^" + std::to_string(n)); - return *type; - } - - static constexpr uint64_t Properties() { - return W::Properties() & - (kLeftSemiring | kRightSemiring | kCommutative | kIdempotent); - } - - PowerWeight Quantize(float delta = kDelta) const { - return PowerWeight(TupleWeight::Quantize(delta)); - } - - ReverseWeight Reverse() const { - return ReverseWeight(TupleWeight::Reverse()); - } -}; - -// Semiring plus operation. -template -inline PowerWeight Plus(const PowerWeight &w1, - const PowerWeight &w2) { - PowerWeight result; - for (size_t i = 0; i < n; ++i) { - result.SetValue(i, Plus(w1.Value(i), w2.Value(i))); - } - return result; -} - -// Semiring times operation. -template -inline PowerWeight Times(const PowerWeight &w1, - const PowerWeight &w2) { - PowerWeight result; - for (size_t i = 0; i < n; ++i) { - result.SetValue(i, Times(w1.Value(i), w2.Value(i))); - } - return result; -} - -// Semiring divide operation. -template -inline PowerWeight Divide(const PowerWeight &w1, - const PowerWeight &w2, - DivideType type = DIVIDE_ANY) { - PowerWeight result; - for (size_t i = 0; i < n; ++i) { - result.SetValue(i, Divide(w1.Value(i), w2.Value(i), type)); - } - return result; -} - -// Semimodule left scalar product. -template -inline PowerWeight Times(const W &scalar, - const PowerWeight &weight) { - PowerWeight result; - for (size_t i = 0; i < n; ++i) { - result.SetValue(i, Times(scalar, weight.Value(i))); - } - return result; -} - -// Semimodule right scalar product. -template -inline PowerWeight Times(const PowerWeight &weight, - const W &scalar) { - PowerWeight result; - for (size_t i = 0; i < n; ++i) { - result.SetValue(i, Times(weight.Value(i), scalar)); - } - return result; -} - -// Semimodule dot product. -template -inline W DotProduct(const PowerWeight &w1, const PowerWeight &w2) { - W result(W::Zero()); - for (size_t i = 0; i < n; ++i) { - result = Plus(result, Times(w1.Value(i), w2.Value(i))); - } - return result; -} - -// This function object generates weights over the Cartesian power of rank -// n over the underlying weight. This is intended primarily for testing. -template -class WeightGenerate> { - public: - using Weight = PowerWeight; - using Generate = WeightGenerate; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true) - : generate_(seed, allow_zero) {} - - Weight operator()() const { - Weight result; - for (size_t i = 0; i < n; ++i) result.SetValue(i, generate_()); - return result; - } - - private: - const Generate generate_; -}; - -} // namespace fst - -#endif // FST_POWER_WEIGHT_H_ diff --git a/contrib/fstlib/fst/product-weight.h b/contrib/fstlib/fst/product-weight.h deleted file mode 100644 index 6f61d72..0000000 --- a/contrib/fstlib/fst/product-weight.h +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Product weight set and associated semiring operation definitions. - -#ifndef FST_PRODUCT_WEIGHT_H_ -#define FST_PRODUCT_WEIGHT_H_ - -#include -#include -#include -#include - -#include -#include - -namespace fst { - -// Product semiring: W1 * W2. -template -class ProductWeight : public PairWeight { - public: - using ReverseWeight = - ProductWeight; - - ProductWeight() = default; - - explicit ProductWeight(const PairWeight &weight) - : PairWeight(weight) {} - - ProductWeight(W1 w1, W2 w2) - : PairWeight(std::move(w1), std::move(w2)) {} - - static const ProductWeight &Zero() { - static const ProductWeight zero(PairWeight::Zero()); - return zero; - } - - static const ProductWeight &One() { - static const ProductWeight one(PairWeight::One()); - return one; - } - - static const ProductWeight &NoWeight() { - static const ProductWeight no_weight(PairWeight::NoWeight()); - return no_weight; - } - - static const std::string &Type() { - static const std::string *const type = - new std::string(W1::Type() + "_X_" + W2::Type()); - return *type; - } - - static constexpr uint64_t Properties() { - return W1::Properties() & W2::Properties() & - (kLeftSemiring | kRightSemiring | kCommutative | kIdempotent); - } - - ProductWeight Quantize(float delta = kDelta) const { - return ProductWeight(PairWeight::Quantize(delta)); - } - - ReverseWeight Reverse() const { - return ReverseWeight(PairWeight::Reverse()); - } -}; - -template -inline ProductWeight Plus(const ProductWeight &w1, - const ProductWeight &w2) { - return ProductWeight(Plus(w1.Value1(), w2.Value1()), - Plus(w1.Value2(), w2.Value2())); -} - -template -inline ProductWeight Times(const ProductWeight &w1, - const ProductWeight &w2) { - return ProductWeight(Times(w1.Value1(), w2.Value1()), - Times(w1.Value2(), w2.Value2())); -} - -template -inline ProductWeight Divide(const ProductWeight &w1, - const ProductWeight &w2, - DivideType typ = DIVIDE_ANY) { - return ProductWeight(Divide(w1.Value1(), w2.Value1(), typ), - Divide(w1.Value2(), w2.Value2(), typ)); -} - -// Specialization for product weight -template -class Adder> { - public: - using Weight = ProductWeight; - - Adder() = default; - - explicit Adder(Weight w) : adder1_(w.Value1()), adder2_(w.Value2()) {} - - Weight Add(const Weight &w) { - adder1_.Add(w.Value1()); - adder2_.Add(w.Value2()); - return Sum(); - } - - Weight Sum() const { return Weight(adder1_.Sum(), adder2_.Sum()); } - - void Reset(Weight w = Weight::Zero()) { - adder1_.Reset(w.Value1()); - adder2_.Reset(w.Value2()); - } - - private: - Adder adder1_; - Adder adder2_; -}; - -// This function object generates weights by calling the underlying generators -// for the template weight types, like all other pair weight types. This is -// intended primarily for testing. -template -class WeightGenerate> { - public: - using Weight = ProductWeight; - using Generate = WeightGenerate>; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true) - : generate_(seed, allow_zero) {} - - Weight operator()() const { return Weight(generate_()); } - - private: - const Generate generate_; -}; - -} // namespace fst - -#endif // FST_PRODUCT_WEIGHT_H_ diff --git a/contrib/fstlib/fst/project.h b/contrib/fstlib/fst/project.h deleted file mode 100644 index 1704547..0000000 --- a/contrib/fstlib/fst/project.h +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to project an FST on to its domain or range. - -#ifndef FST_PROJECT_H_ -#define FST_PROJECT_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// This specifies whether to project on input or output. -enum class ProjectType { INPUT = 1, OUTPUT = 2 }; -OPENFST_DEPRECATED("Use `ProjectType::INPUT` instead.") -inline constexpr ProjectType PROJECT_INPUT = ProjectType::INPUT; -OPENFST_DEPRECATED("Use `ProjectType::OUTPUT` instead.") -inline constexpr ProjectType PROJECT_OUTPUT = ProjectType::OUTPUT; - -// Mapper to implement projection per arc. -template -class ProjectMapper { - public: - using FromArc = A; - using ToArc = A; - - constexpr explicit ProjectMapper(ProjectType project_type) - : project_type_(project_type) {} - - ToArc operator()(const FromArc &arc) const { - const auto label = - project_type_ == ProjectType::INPUT ? arc.ilabel : arc.olabel; - return ToArc(label, label, arc.weight, arc.nextstate); - } - - constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } - - constexpr MapSymbolsAction InputSymbolsAction() const { - return project_type_ == ProjectType::INPUT ? MAP_COPY_SYMBOLS - : MAP_CLEAR_SYMBOLS; - } - - constexpr MapSymbolsAction OutputSymbolsAction() const { - return project_type_ == ProjectType::OUTPUT ? MAP_COPY_SYMBOLS - : MAP_CLEAR_SYMBOLS; - } - - constexpr uint64_t Properties(uint64_t props) const { - return ProjectProperties(props, project_type_ == ProjectType::INPUT); - } - - private: - const ProjectType project_type_; -}; - -// Projects an FST onto its domain or range by either copying each arcs' input -// label to the output label or vice versa. -// -// Complexity: -// -// Time: O(V + E) -// Space: O(1) -// -// where V is the number of states and E is the number of arcs. -template -inline void Project(const Fst &ifst, MutableFst *ofst, - ProjectType project_type) { - ArcMap(ifst, ofst, ProjectMapper(project_type)); - switch (project_type) { - case ProjectType::INPUT: - ofst->SetOutputSymbols(ifst.InputSymbols()); - return; - case ProjectType::OUTPUT: - ofst->SetInputSymbols(ifst.OutputSymbols()); - return; - } -} - -// Destructive variant of the above. -template -inline void Project(MutableFst *fst, ProjectType project_type) { - ArcMap(fst, ProjectMapper(project_type)); - switch (project_type) { - case ProjectType::INPUT: - fst->SetOutputSymbols(fst->InputSymbols()); - return; - case ProjectType::OUTPUT: - fst->SetInputSymbols(fst->OutputSymbols()); - return; - } -} - -// Projects an FST onto its domain or range by either copying each arc's input -// label to the output label or vice versa. This version is a delayed FST. -// -// Complexity: -// -// Time: O(v + e) -// Space: O(1) -// -// where v is the number of states visited and e is the number of arcs visited. -// Constant time and to visit an input state or arc is assumed and exclusive of -// caching. -template -class ProjectFst : public ArcMapFst> { - public: - using FromArc = A; - using ToArc = A; - - using Impl = internal::ArcMapFstImpl>; - - ProjectFst(const Fst &fst, ProjectType project_type) - : ArcMapFst>(fst, ProjectMapper(project_type)) { - if (project_type == ProjectType::INPUT) { - GetMutableImpl()->SetOutputSymbols(fst.InputSymbols()); - } - if (project_type == ProjectType::OUTPUT) { - GetMutableImpl()->SetInputSymbols(fst.OutputSymbols()); - } - } - - // See Fst<>::Copy() for doc. - ProjectFst(const ProjectFst &fst, bool safe = false) - : ArcMapFst>(fst, safe) {} - - // Gets a copy of this ProjectFst. See Fst<>::Copy() for further doc. - ProjectFst *Copy(bool safe = false) const override { - return new ProjectFst(*this, safe); - } - - private: - using ImplToFst::GetMutableImpl; -}; - -// Specialization for ProjectFst. -template -class StateIterator> - : public StateIterator>> { - public: - explicit StateIterator(const ProjectFst &fst) - : StateIterator>>(fst) {} -}; - -// Specialization for ProjectFst. -template -class ArcIterator> - : public ArcIterator>> { - public: - using StateId = typename A::StateId; - - ArcIterator(const ProjectFst &fst, StateId s) - : ArcIterator>>(fst, s) {} -}; - -// Useful alias when using StdArc. -using StdProjectFst = ProjectFst; - -} // namespace fst - -#endif // FST_PROJECT_H_ diff --git a/contrib/fstlib/fst/properties.h b/contrib/fstlib/fst/properties.h deleted file mode 100644 index 897621a..0000000 --- a/contrib/fstlib/fst/properties.h +++ /dev/null @@ -1,531 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST property bits. - -#ifndef FST_PROPERTIES_H_ -#define FST_PROPERTIES_H_ - -#include - -#include -#include -#include - -#include -#include -#include - -namespace fst { - -// The property bits here assert facts about an FST. If individual bits are -// added, then the composite properties below, the property functions and -// property names in properties.cc, and TestProperties() in test-properties.h -// should be updated. - -// BINARY PROPERTIES -// -// For each property below, there is a single bit. If it is set, the property is -// true. If it is not set, the property is false. - -// The Fst is an ExpandedFst. -inline constexpr uint64_t kExpanded = 0x0000000000000001ULL; - -// The Fst is a MutableFst. -inline constexpr uint64_t kMutable = 0x0000000000000002ULL; - -// An error was detected while constructing/using the FST. -inline constexpr uint64_t kError = 0x0000000000000004ULL; - -// TRINARY PROPERTIES -// -// For each of these properties below there is a pair of property bits, one -// positive and one negative. If the positive bit is set, the property is true. -// If the negative bit is set, the property is false. If neither is set, the -// property has unknown value. Both should never be simultaneously set. The -// individual positive and negative bit pairs should be adjacent with the -// positive bit at an odd and lower position. - -// ilabel == olabel for each arc. -inline constexpr uint64_t kAcceptor = 0x0000000000010000ULL; -// ilabel != olabel for some arc. -inline constexpr uint64_t kNotAcceptor = 0x0000000000020000ULL; - -// ilabels unique leaving each state. -inline constexpr uint64_t kIDeterministic = 0x0000000000040000ULL; -// ilabels not unique leaving some state. -inline constexpr uint64_t kNonIDeterministic = 0x0000000000080000ULL; - -// olabels unique leaving each state. -inline constexpr uint64_t kODeterministic = 0x0000000000100000ULL; -// olabels not unique leaving some state. -inline constexpr uint64_t kNonODeterministic = 0x0000000000200000ULL; - -// FST has input/output epsilons. -inline constexpr uint64_t kEpsilons = 0x0000000000400000ULL; -// FST has no input/output epsilons. -inline constexpr uint64_t kNoEpsilons = 0x0000000000800000ULL; - -// FST has input epsilons. -inline constexpr uint64_t kIEpsilons = 0x0000000001000000ULL; -// FST has no input epsilons. -inline constexpr uint64_t kNoIEpsilons = 0x0000000002000000ULL; - -// FST has output epsilons. -inline constexpr uint64_t kOEpsilons = 0x0000000004000000ULL; -// FST has no output epsilons. -inline constexpr uint64_t kNoOEpsilons = 0x0000000008000000ULL; - -// ilabels sorted wrt < for each state. -inline constexpr uint64_t kILabelSorted = 0x0000000010000000ULL; -// ilabels not sorted wrt < for some state. -inline constexpr uint64_t kNotILabelSorted = 0x0000000020000000ULL; - -// olabels sorted wrt < for each state. -inline constexpr uint64_t kOLabelSorted = 0x0000000040000000ULL; -// olabels not sorted wrt < for some state. -inline constexpr uint64_t kNotOLabelSorted = 0x0000000080000000ULL; - -// Non-trivial arc or final weights. -inline constexpr uint64_t kWeighted = 0x0000000100000000ULL; -// Only trivial arc and final weights. -inline constexpr uint64_t kUnweighted = 0x0000000200000000ULL; - -// FST has cycles. -inline constexpr uint64_t kCyclic = 0x0000000400000000ULL; -// FST has no cycles. -inline constexpr uint64_t kAcyclic = 0x0000000800000000ULL; - -// FST has cycles containing the initial state. -inline constexpr uint64_t kInitialCyclic = 0x0000001000000000ULL; -// FST has no cycles containing the initial state. -inline constexpr uint64_t kInitialAcyclic = 0x0000002000000000ULL; - -// FST is topologically sorted. -inline constexpr uint64_t kTopSorted = 0x0000004000000000ULL; -// FST is not topologically sorted. -inline constexpr uint64_t kNotTopSorted = 0x0000008000000000ULL; - -// All states reachable from the initial state. -inline constexpr uint64_t kAccessible = 0x0000010000000000ULL; -// Not all states reachable from the initial state. -inline constexpr uint64_t kNotAccessible = 0x0000020000000000ULL; - -// All states can reach a final state. -inline constexpr uint64_t kCoAccessible = 0x0000040000000000ULL; -// Not all states can reach a final state. -inline constexpr uint64_t kNotCoAccessible = 0x0000080000000000ULL; - -// If NumStates() > 0, then state 0 is initial, state NumStates() - 1 is final, -// there is a transition from each non-final state i to state i + 1, and there -// are no other transitions. -inline constexpr uint64_t kString = 0x0000100000000000ULL; - -// Not a string FST. -inline constexpr uint64_t kNotString = 0x0000200000000000ULL; - -// FST has at least one weighted cycle. -inline constexpr uint64_t kWeightedCycles = 0x0000400000000000ULL; - -// FST has no weighted cycles. Any cycles that may be present are unweighted. -inline constexpr uint64_t kUnweightedCycles = 0x0000800000000000ULL; - -// COMPOSITE PROPERTIES - -// Properties of an empty machine. -inline constexpr uint64_t kNullProperties = - kAcceptor | kIDeterministic | kODeterministic | kNoEpsilons | kNoIEpsilons | - kNoOEpsilons | kILabelSorted | kOLabelSorted | kUnweighted | kAcyclic | - kInitialAcyclic | kTopSorted | kAccessible | kCoAccessible | kString | - kUnweightedCycles; - -// Properties of a string FST compiled into a string. -inline constexpr uint64_t kCompiledStringProperties = - kAcceptor | kString | kUnweighted | kIDeterministic | kODeterministic | - kILabelSorted | kOLabelSorted | kAcyclic | kInitialAcyclic | - kUnweightedCycles | kTopSorted | kAccessible | kCoAccessible; - -// Properties that are preserved when an FST is copied. -inline constexpr uint64_t kCopyProperties = - kError | kAcceptor | kNotAcceptor | kIDeterministic | kNonIDeterministic | - kODeterministic | kNonODeterministic | kEpsilons | kNoEpsilons | - kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | kILabelSorted | - kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | kWeighted | - kUnweighted | kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | - kTopSorted | kNotTopSorted | kAccessible | kNotAccessible | kCoAccessible | - kNotCoAccessible | kString | kNotString | kWeightedCycles | - kUnweightedCycles; - -// Properties that are intrinsic to the FST. -inline constexpr uint64_t kIntrinsicProperties = - kExpanded | kMutable | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kILabelSorted | kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | - kWeighted | kUnweighted | kCyclic | kAcyclic | kInitialCyclic | - kInitialAcyclic | kTopSorted | kNotTopSorted | kAccessible | - kNotAccessible | kCoAccessible | kNotCoAccessible | kString | kNotString | - kWeightedCycles | kUnweightedCycles; - -// Properties that are (potentially) extrinsic to the FST. -inline constexpr uint64_t kExtrinsicProperties = kError; - -// Properties that are preserved when an FST start state is set. -inline constexpr uint64_t kSetStartProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kILabelSorted | kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | - kWeighted | kUnweighted | kCyclic | kAcyclic | kTopSorted | kNotTopSorted | - kCoAccessible | kNotCoAccessible | kWeightedCycles | kUnweightedCycles; - -// Properties that are preserved when an FST final weight is set. -inline constexpr uint64_t kSetFinalProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kILabelSorted | kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | - kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | kTopSorted | - kNotTopSorted | kAccessible | kNotAccessible | kWeightedCycles | - kUnweightedCycles; - -// Properties that are preserved when an FST state is added. -inline constexpr uint64_t kAddStateProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kILabelSorted | kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | - kWeighted | kUnweighted | kCyclic | kAcyclic | kInitialCyclic | - kInitialAcyclic | kTopSorted | kNotTopSorted | kNotAccessible | - kNotCoAccessible | kNotString | kWeightedCycles | kUnweightedCycles; - -// Properties that are preserved when an FST arc is added. -inline constexpr uint64_t kAddArcProperties = - kExpanded | kMutable | kError | kNotAcceptor | kNonIDeterministic | - kNonODeterministic | kEpsilons | kIEpsilons | kOEpsilons | - kNotILabelSorted | kNotOLabelSorted | kWeighted | kCyclic | kInitialCyclic | - kNotTopSorted | kAccessible | kCoAccessible | kWeightedCycles; - -// Properties that are preserved when an FST arc is set. -inline constexpr uint64_t kSetArcProperties = kExpanded | kMutable | kError; - -// Properties that are preserved when FST states are deleted. -inline constexpr uint64_t kDeleteStatesProperties = - kExpanded | kMutable | kError | kAcceptor | kIDeterministic | - kODeterministic | kNoEpsilons | kNoIEpsilons | kNoOEpsilons | - kILabelSorted | kOLabelSorted | kUnweighted | kAcyclic | kInitialAcyclic | - kTopSorted | kUnweightedCycles; - -// Properties that are preserved when FST arcs are deleted. -inline constexpr uint64_t kDeleteArcsProperties = - kExpanded | kMutable | kError | kAcceptor | kIDeterministic | - kODeterministic | kNoEpsilons | kNoIEpsilons | kNoOEpsilons | - kILabelSorted | kOLabelSorted | kUnweighted | kAcyclic | kInitialAcyclic | - kTopSorted | kNotAccessible | kNotCoAccessible | kUnweightedCycles; - -// Properties that are preserved when an FST's states are reordered. -inline constexpr uint64_t kStateSortProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kILabelSorted | kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | - kWeighted | kUnweighted | kCyclic | kAcyclic | kInitialCyclic | - kInitialAcyclic | kAccessible | kNotAccessible | kCoAccessible | - kNotCoAccessible | kWeightedCycles | kUnweightedCycles; - -// Properties that are preserved when an FST's arcs are reordered. -inline constexpr uint64_t kArcSortProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kWeighted | kUnweighted | kCyclic | kAcyclic | kInitialCyclic | - kInitialAcyclic | kTopSorted | kNotTopSorted | kAccessible | - kNotAccessible | kCoAccessible | kNotCoAccessible | kString | kNotString | - kWeightedCycles | kUnweightedCycles; - -// Properties that are preserved when an FST's input labels are changed. -inline constexpr uint64_t kILabelInvariantProperties = - kExpanded | kMutable | kError | kODeterministic | kNonODeterministic | - kOEpsilons | kNoOEpsilons | kOLabelSorted | kNotOLabelSorted | kWeighted | - kUnweighted | kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | - kTopSorted | kNotTopSorted | kAccessible | kNotAccessible | kCoAccessible | - kNotCoAccessible | kString | kNotString | kWeightedCycles | - kUnweightedCycles; - -// Properties that are preserved when an FST's output labels are changed. -inline constexpr uint64_t kOLabelInvariantProperties = - kExpanded | kMutable | kError | kIDeterministic | kNonIDeterministic | - kIEpsilons | kNoIEpsilons | kILabelSorted | kNotILabelSorted | kWeighted | - kUnweighted | kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | - kTopSorted | kNotTopSorted | kAccessible | kNotAccessible | kCoAccessible | - kNotCoAccessible | kString | kNotString | kWeightedCycles | - kUnweightedCycles; - -// Properties that are preserved when an FST's weights are changed. This -// assumes that the set of states that are non-final is not changed. -inline constexpr uint64_t kWeightInvariantProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kNonIDeterministic | kODeterministic | kNonODeterministic | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | kNoOEpsilons | - kILabelSorted | kNotILabelSorted | kOLabelSorted | kNotOLabelSorted | - kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | kTopSorted | - kNotTopSorted | kAccessible | kNotAccessible | kCoAccessible | - kNotCoAccessible | kString | kNotString; - -// Properties that are preserved when a superfinal state is added and an FST's -// final weights are directed to it via new transitions. -inline constexpr uint64_t kAddSuperFinalProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | - kNonIDeterministic | kNonODeterministic | kEpsilons | kIEpsilons | - kOEpsilons | kNotILabelSorted | kNotOLabelSorted | kWeighted | kUnweighted | - kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | kNotTopSorted | - kNotAccessible | kCoAccessible | kNotCoAccessible | kNotString | - kWeightedCycles | kUnweightedCycles; - -// Properties that are preserved when a superfinal state is removed and the -// epsilon transitions directed to it are made final weights. -inline constexpr uint64_t kRmSuperFinalProperties = - kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | kIDeterministic | - kODeterministic | kNoEpsilons | kNoIEpsilons | kNoOEpsilons | - kILabelSorted | kOLabelSorted | kWeighted | kUnweighted | kCyclic | - kAcyclic | kInitialCyclic | kInitialAcyclic | kTopSorted | kAccessible | - kCoAccessible | kNotCoAccessible | kString | kWeightedCycles | - kUnweightedCycles; - -// All binary properties. -inline constexpr uint64_t kBinaryProperties = 0x0000000000000007ULL; - -// All trinary properties. -inline constexpr uint64_t kTrinaryProperties = 0x0000ffffffff0000ULL; - -// COMPUTED PROPERTIES - -// 1st bit of trinary properties. -inline constexpr uint64_t kPosTrinaryProperties = - kTrinaryProperties & 0x5555555555555555ULL; - -// 2nd bit of trinary properties. -inline constexpr uint64_t kNegTrinaryProperties = - kTrinaryProperties & 0xaaaaaaaaaaaaaaaaULL; - -// All properties. -inline constexpr uint64_t kFstProperties = - kBinaryProperties | kTrinaryProperties; - -// PROPERTY FUNCTIONS and STRING NAMES (defined in properties.cc). - -// Below are functions for getting property bit vectors when executing -// mutation operations. -inline uint64_t SetStartProperties(uint64_t inprops); - -template -uint64_t SetFinalProperties(uint64_t inprops, const Weight &old_weight, - const Weight &new_weight); - -inline uint64_t AddStateProperties(uint64_t inprops); - -template -uint64_t AddArcProperties(uint64_t inprops, typename A::StateId s, const A &arc, - const A *prev_arc); - -inline uint64_t DeleteStatesProperties(uint64_t inprops); - -inline uint64_t DeleteAllStatesProperties(uint64_t inprops, - uint64_t staticProps); - -inline uint64_t DeleteArcsProperties(uint64_t inprops); - -uint64_t ClosureProperties(uint64_t inprops, bool star, bool delayed = false); - -uint64_t ComplementProperties(uint64_t inprops); - -uint64_t ComposeProperties(uint64_t inprops1, uint64_t inprops2); - -uint64_t ConcatProperties(uint64_t inprops1, uint64_t inprops2, - bool delayed = false); - -uint64_t DeterminizeProperties(uint64_t inprops, bool has_subsequential_label, - bool distinct_psubsequential_labels); - -uint64_t FactorWeightProperties(uint64_t inprops); - -uint64_t InvertProperties(uint64_t inprops); - -uint64_t ProjectProperties(uint64_t inprops, bool project_input); - -uint64_t RandGenProperties(uint64_t inprops, bool weighted); - -uint64_t RelabelProperties(uint64_t inprops); - -uint64_t ReplaceProperties(const std::vector &inprops, size_t root, - bool epsilon_on_call, bool epsilon_on_return, - bool out_epsilon_on_call, bool out_epsilon_on_return, - bool replace_transducer, bool no_empty_fst, - bool all_ilabel_sorted, bool all_olabel_sorted, - bool all_negative_or_dense); - -uint64_t ReverseProperties(uint64_t inprops, bool has_superinitial); - -uint64_t ReweightProperties(uint64_t inprops, bool added_start_epsilon); - -uint64_t RmEpsilonProperties(uint64_t inprops, bool delayed = false); - -uint64_t ShortestPathProperties(uint64_t props, bool tree = false); - -uint64_t SynchronizeProperties(uint64_t inprops); - -uint64_t UnionProperties(uint64_t inprops1, uint64_t inprops2, - bool delayed = false); - -// Definitions of inlined functions. - -uint64_t SetStartProperties(uint64_t inprops) { - auto outprops = inprops & kSetStartProperties; - if (inprops & kAcyclic) { - outprops |= kInitialAcyclic; - } - return outprops; -} - -uint64_t AddStateProperties(uint64_t inprops) { - return inprops & kAddStateProperties; -} - -uint64_t DeleteStatesProperties(uint64_t inprops) { - return inprops & kDeleteStatesProperties; -} - -uint64_t DeleteAllStatesProperties(uint64_t inprops, uint64_t staticprops) { - const auto outprops = inprops & kError; - return outprops | kNullProperties | staticprops; -} - -uint64_t DeleteArcsProperties(uint64_t inprops) { - return inprops & kDeleteArcsProperties; -} - -// Definitions of template functions. - -template -uint64_t SetFinalProperties(uint64_t inprops, const Weight &old_weight, - const Weight &new_weight) { - auto outprops = inprops; - if (old_weight != Weight::Zero() && old_weight != Weight::One()) { - outprops &= ~kWeighted; - } - if (new_weight != Weight::Zero() && new_weight != Weight::One()) { - outprops |= kWeighted; - outprops &= ~kUnweighted; - } - outprops &= kSetFinalProperties | kWeighted | kUnweighted; - return outprops; -} - -/// Gets the properties for the MutableFst::AddArc method. -/// -/// \param inprops the current properties of the FST -/// \param s the ID of the state to which an arc is being added. -/// \param arc the arc being added to the state with the specified ID -/// \param prev_arc the previously-added (or "last") arc of state s, or nullptr -// if s currently has no arcs. -template -uint64_t AddArcProperties(uint64_t inprops, typename Arc::StateId s, - const Arc &arc, const Arc *prev_arc) { - using Weight = typename Arc::Weight; - auto outprops = inprops; - if (arc.ilabel != arc.olabel) { - outprops |= kNotAcceptor; - outprops &= ~kAcceptor; - } - if (arc.ilabel == 0) { - outprops |= kIEpsilons; - outprops &= ~kNoIEpsilons; - if (arc.olabel == 0) { - outprops |= kEpsilons; - outprops &= ~kNoEpsilons; - } - } - if (arc.olabel == 0) { - outprops |= kOEpsilons; - outprops &= ~kNoOEpsilons; - } - if (prev_arc) { - if (prev_arc->ilabel > arc.ilabel) { - outprops |= kNotILabelSorted; - outprops &= ~kILabelSorted; - } - if (prev_arc->olabel > arc.olabel) { - outprops |= kNotOLabelSorted; - outprops &= ~kOLabelSorted; - } - } - if (arc.weight != Weight::Zero() && arc.weight != Weight::One()) { - outprops |= kWeighted; - outprops &= ~kUnweighted; - } - if (arc.nextstate <= s) { - outprops |= kNotTopSorted; - outprops &= ~kTopSorted; - } - outprops &= kAddArcProperties | kAcceptor | kNoEpsilons | kNoIEpsilons | - kNoOEpsilons | kILabelSorted | kOLabelSorted | kUnweighted | - kTopSorted; - if (outprops & kTopSorted) { - outprops |= kAcyclic | kInitialAcyclic; - } - return outprops; -} - -namespace internal { - -extern const std::string_view PropertyNames[]; - -// For a binary property, the bit is always returned set. For a trinary (i.e., -// two-bit) property, both bits are returned set iff either corresponding input -// bit is set. -inline uint64_t KnownProperties(uint64_t props) { - return kBinaryProperties | (props & kTrinaryProperties) | - ((props & kPosTrinaryProperties) << 1) | - ((props & kNegTrinaryProperties) >> 1); -} - -// Tests compatibility between two sets of properties. -inline bool CompatProperties(uint64_t props1, uint64_t props2) { - const auto known_props1 = KnownProperties(props1); - const auto known_props2 = KnownProperties(props2); - const auto known_props = known_props1 & known_props2; - const auto incompat_props = (props1 & known_props) ^ (props2 & known_props); - if (incompat_props) { - uint64_t prop = 1; - for (int i = 0; i < 64; ++i, prop <<= 1) { - if (prop & incompat_props) { - LOG(ERROR) << "CompatProperties: Mismatch: " - << internal::PropertyNames[i] - << ": props1 = " << (props1 & prop ? "true" : "false") - << ", props2 = " << (props2 & prop ? "true" : "false"); - } - } - return false; - } else { - return true; - } -} - -} // namespace internal -} // namespace fst - -#endif // FST_PROPERTIES_H_ diff --git a/contrib/fstlib/fst/prune.h b/contrib/fstlib/fst/prune.h deleted file mode 100644 index 3d20872..0000000 --- a/contrib/fstlib/fst/prune.h +++ /dev/null @@ -1,338 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions implementing pruning. - -#ifndef FST_PRUNE_H_ -#define FST_PRUNE_H_ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { -namespace internal { - -template -class PruneCompare { - public: - PruneCompare(const std::vector &idistance, - const std::vector &fdistance) - : idistance_(idistance), fdistance_(fdistance) {} - - bool operator()(const StateId x, const StateId y) const { - const auto wx = Times(IDistance(x), FDistance(x)); - const auto wy = Times(IDistance(y), FDistance(y)); - return less_(wx, wy); - } - - private: - Weight IDistance(const StateId s) const { - return s < idistance_.size() ? idistance_[s] : Weight::Zero(); - } - - Weight FDistance(const StateId s) const { - return s < fdistance_.size() ? fdistance_[s] : Weight::Zero(); - } - - const std::vector &idistance_; - const std::vector &fdistance_; - NaturalLess less_; -}; - -} // namespace internal - -template -struct PruneOptions { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit PruneOptions(const Weight &weight_threshold = Weight::Zero(), - StateId state_threshold = kNoStateId, - ArcFilter filter = ArcFilter(), - std::vector *distance = nullptr, - float delta = kDelta, bool threshold_initial = false) - : weight_threshold(std::move(weight_threshold)), - state_threshold(state_threshold), - filter(std::move(filter)), - distance(distance), - delta(delta), - threshold_initial(threshold_initial) {} - - // Pruning weight threshold. - Weight weight_threshold; - // Pruning state threshold. - StateId state_threshold; - // Arc filter. - ArcFilter filter; - // If non-zero, passes in pre-computed shortest distance to final states. - const std::vector *distance; - // Determines the degree of convergence required when computing shortest - // distances. - float delta; - // Determines if the shortest path weight is left (true) or right - // (false) multiplied by the threshold to get the limit for - // keeping a state or arc (matters if the semiring is not - // commutative). - bool threshold_initial; -}; - -// Pruning algorithm: this version modifies its input and it takes an options -// class as an argument. After pruning the FST contains states and arcs that -// belong to a successful path in the FST whose weight is no more than the -// weight of the shortest path Times() the provided weight threshold. When the -// state threshold is not kNoStateId, the output FST is further restricted to -// have no more than the number of states in opts.state_threshold. Weights must -// have the path property. The weight of any cycle needs to be bounded; i.e., -// -// Plus(weight, Weight::One()) == Weight::One() -template -void Prune(MutableFst *fst, const PruneOptions &opts = - PruneOptions()) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - static_assert(IsPath::value, "Weight must have path property."); - using StateHeap = Heap>; - auto ns = fst->NumStates(); - if (ns < 1) return; - std::vector idistance(ns, Weight::Zero()); - std::vector tmp; - if (!opts.distance) { - tmp.reserve(ns); - ShortestDistance(*fst, &tmp, true, opts.delta); - } - const auto *fdistance = opts.distance ? opts.distance : &tmp; - if ((opts.state_threshold == 0) || (fdistance->size() <= fst->Start()) || - ((*fdistance)[fst->Start()] == Weight::Zero())) { - fst->DeleteStates(); - return; - } - internal::PruneCompare compare(idistance, *fdistance); - StateHeap heap(compare); - std::vector visited(ns, false); - std::vector enqueued(ns, StateHeap::kNoKey); - std::vector dead; - dead.push_back(fst->AddState()); - NaturalLess less; - auto s = fst->Start(); - const auto limit = opts.threshold_initial - ? Times(opts.weight_threshold, (*fdistance)[s]) - : Times((*fdistance)[s], opts.weight_threshold); - StateId num_visited = 0; - - if (!less(limit, (*fdistance)[s])) { - idistance[s] = Weight::One(); - enqueued[s] = heap.Insert(s); - ++num_visited; - } - while (!heap.Empty()) { - s = heap.Top(); - heap.Pop(); - enqueued[s] = StateHeap::kNoKey; - visited[s] = true; - if (less(limit, Times(idistance[s], fst->Final(s)))) { - fst->SetFinal(s, Weight::Zero()); - } - for (MutableArcIterator> aiter(fst, s); !aiter.Done(); - aiter.Next()) { - auto arc = aiter.Value(); // Copy intended. - if (!opts.filter(arc)) continue; - const auto weight = - Times(Times(idistance[s], arc.weight), - arc.nextstate < fdistance->size() ? (*fdistance)[arc.nextstate] - : Weight::Zero()); - if (less(limit, weight)) { - arc.nextstate = dead[0]; - aiter.SetValue(arc); - continue; - } - if (less(Times(idistance[s], arc.weight), idistance[arc.nextstate])) { - idistance[arc.nextstate] = Times(idistance[s], arc.weight); - } - if (visited[arc.nextstate]) continue; - if ((opts.state_threshold != kNoStateId) && - (num_visited >= opts.state_threshold)) { - continue; - } - if (enqueued[arc.nextstate] == StateHeap::kNoKey) { - enqueued[arc.nextstate] = heap.Insert(arc.nextstate); - ++num_visited; - } else { - heap.Update(enqueued[arc.nextstate], arc.nextstate); - } - } - } - for (StateId i = 0; i < visited.size(); ++i) { - if (!visited[i]) dead.push_back(i); - } - fst->DeleteStates(dead); -} - -// Pruning algorithm: this version modifies its input and takes the -// pruning threshold as an argument. It deletes states and arcs in the -// FST that do not belong to a successful path whose weight is more -// than the weight of the shortest path Times() the provided weight -// threshold. When the state threshold is not kNoStateId, the output -// FST is further restricted to have no more than the number of states -// in opts.state_threshold. Weights must have the path property. The -// weight of any cycle needs to be bounded; i.e., -// -// Plus(weight, Weight::One()) == Weight::One() -template -void Prune(MutableFst *fst, typename Arc::Weight weight_threshold, - typename Arc::StateId state_threshold = kNoStateId, - float delta = kDelta) { - const PruneOptions> opts( - weight_threshold, state_threshold, AnyArcFilter(), nullptr, delta); - 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. The -// output FST contains states and arcs that belong to a successful -// path in the input FST whose weight is more than the weight of the -// shortest path Times() the provided weight threshold. When the state -// threshold is not kNoStateId, the output FST is further restricted -// to have no more than the number of states in -// opts.state_threshold. Weights have the path property. The weight -// of any cycle needs to be bounded; i.e., -// -// Plus(weight, Weight::One()) == Weight::One() -template -void Prune( - const Fst &ifst, MutableFst *ofst, - const PruneOptions &opts = PruneOptions()) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - static_assert(IsPath::value, "Weight must have path property."); - using StateHeap = Heap>; - ofst->DeleteStates(); - ofst->SetInputSymbols(ifst.InputSymbols()); - ofst->SetOutputSymbols(ifst.OutputSymbols()); - if (ifst.Start() == kNoStateId) return; - NaturalLess less; - if (less(opts.weight_threshold, Weight::One()) || - (opts.state_threshold == 0)) { - return; - } - std::vector idistance; - std::vector tmp; - if (!opts.distance) ShortestDistance(ifst, &tmp, true, opts.delta); - const auto *fdistance = opts.distance ? opts.distance : &tmp; - if ((fdistance->size() <= ifst.Start()) || - ((*fdistance)[ifst.Start()] == Weight::Zero())) { - return; - } - internal::PruneCompare compare(idistance, *fdistance); - StateHeap heap(compare); - std::vector copy; - std::vector enqueued; - std::vector visited; - auto s = ifst.Start(); - const auto limit = opts.threshold_initial - ? Times(opts.weight_threshold, (*fdistance)[s]) - : Times((*fdistance)[s], opts.weight_threshold); - while (copy.size() <= s) copy.push_back(kNoStateId); - copy[s] = ofst->AddState(); - ofst->SetStart(copy[s]); - while (idistance.size() <= s) idistance.push_back(Weight::Zero()); - idistance[s] = Weight::One(); - while (enqueued.size() <= s) { - enqueued.push_back(StateHeap::kNoKey); - visited.push_back(false); - } - enqueued[s] = heap.Insert(s); - while (!heap.Empty()) { - s = heap.Top(); - heap.Pop(); - enqueued[s] = StateHeap::kNoKey; - visited[s] = true; - if (!less(limit, Times(idistance[s], ifst.Final(s)))) { - ofst->SetFinal(copy[s], ifst.Final(s)); - } - for (ArcIterator> aiter(ifst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - if (!opts.filter(arc)) continue; - const auto weight = - Times(Times(idistance[s], arc.weight), - arc.nextstate < fdistance->size() ? (*fdistance)[arc.nextstate] - : Weight::Zero()); - if (less(limit, weight)) continue; - if ((opts.state_threshold != kNoStateId) && - (ofst->NumStates() >= opts.state_threshold)) { - continue; - } - while (idistance.size() <= arc.nextstate) { - idistance.push_back(Weight::Zero()); - } - if (less(Times(idistance[s], arc.weight), idistance[arc.nextstate])) { - idistance[arc.nextstate] = Times(idistance[s], arc.weight); - } - while (copy.size() <= arc.nextstate) copy.push_back(kNoStateId); - if (copy[arc.nextstate] == kNoStateId) { - copy[arc.nextstate] = ofst->AddState(); - } - ofst->AddArc(copy[s], Arc(arc.ilabel, arc.olabel, arc.weight, - copy[arc.nextstate])); - while (enqueued.size() <= arc.nextstate) { - enqueued.push_back(StateHeap::kNoKey); - visited.push_back(false); - } - if (visited[arc.nextstate]) continue; - if (enqueued[arc.nextstate] == StateHeap::kNoKey) { - enqueued[arc.nextstate] = heap.Insert(arc.nextstate); - } else { - heap.Update(enqueued[arc.nextstate], arc.nextstate); - } - } - } -} - -// Pruning algorithm: this version writes the pruned input FST to an -// output MutableFst and simply takes the pruning threshold as an -// argument. The output FST contains states and arcs that belong to a -// successful path in the input FST whose weight is no more than the -// weight of the shortest path Times() the provided weight -// threshold. When the state threshold is not kNoStateId, the output -// FST is further restricted to have no more than the number of states -// in opts.state_threshold. Weights must have the path property. The -// weight of any cycle needs to be bounded; i.e., -// -// Plus(weight, Weight::One()) = Weight::One(); -template -void Prune(const Fst &ifst, MutableFst *ofst, - typename Arc::Weight weight_threshold, - typename Arc::StateId state_threshold = kNoStateId, - float delta = kDelta) { - const PruneOptions> opts( - weight_threshold, state_threshold, AnyArcFilter(), nullptr, delta); - Prune(ifst, ofst, opts); -} - -} // namespace fst - -#endif // FST_PRUNE_H_ diff --git a/contrib/fstlib/fst/push.h b/contrib/fstlib/fst/push.h deleted file mode 100644 index aa50bb6..0000000 --- a/contrib/fstlib/fst/push.h +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to reweight/push an FST, and utility functions to weigh and reweight -// an FST. - -#ifndef FST_PUSH_H_ -#define FST_PUSH_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Computes the total weight (sum of the weights of all accepting paths) from -// the output of ShortestDistance, using the shortest distance from the final -// state when reverse is true and from the initial state otherwise. -template -typename Arc::Weight ComputeTotalWeight( - const Fst &fst, const std::vector &distance, - bool reverse) { - if (reverse) { - return fst.Start() < distance.size() ? distance[fst.Start()] - : Arc::Weight::Zero(); - } - auto sum = Arc::Weight::Zero(); - for (typename Arc::StateId s = 0; s < distance.size(); ++s) { - sum = Plus(sum, Times(distance[s], fst.Final(s))); - } - return sum; -} - -// Divides the weight of every accepting path by a fixed weight. This weight -// is also divided at the final state if at_final is true and at the initial -// state otherwise. -template -void RemoveWeight(MutableFst *fst, const typename Arc::Weight &weight, - bool at_final) { - using Weight = typename Arc::Weight; - if ((weight == Weight::One()) || (weight == Weight::Zero())) return; - if (at_final) { - for (StateIterator> siter(*fst); !siter.Done(); - siter.Next()) { - fst->SetFinal(siter.Value(), - Divide(fst->Final(siter.Value()), weight, DIVIDE_RIGHT)); - } - } else { - const auto start = fst->Start(); - for (MutableArcIterator> aiter(fst, start); !aiter.Done(); - aiter.Next()) { - auto arc = aiter.Value(); - arc.weight = Divide(arc.weight, weight, DIVIDE_LEFT); - aiter.SetValue(arc); - } - fst->SetFinal(start, Divide(fst->Final(start), weight, DIVIDE_LEFT)); - } -} - -// Pushes the weights in FST in the requested direction. If pushing towards the -// initial state, the sum of the weight of the outgoing transitions and final -// weight at a non-initial state is equal to One() in the resulting machine. If -// pushing towards the final state, the same property holds on the reverse -// machine. -// -// Weight needs to be left distributive when pushing towards the initial state -// and right distributive when pushing towards the final states. -template -void Push(MutableFst *fst, ReweightType type = REWEIGHT_TO_INITIAL, - float delta = kShortestDelta, bool remove_total_weight = false) { - using Weight = typename Arc::Weight; - std::vector distance; - const bool reverse = type == REWEIGHT_TO_INITIAL; - ShortestDistance(*fst, &distance, reverse, delta); - if (remove_total_weight) { - const auto total_weight = ComputeTotalWeight(*fst, distance, reverse); - Reweight(fst, distance, type); - RemoveWeight(fst, total_weight, !reverse); - } else { - Reweight(fst, distance, type); - } -} - -inline constexpr uint8_t kPushWeights = 0x01; -inline constexpr uint8_t kPushLabels = 0x02; -inline constexpr uint8_t kPushRemoveTotalWeight = 0x04; -inline constexpr uint8_t kPushRemoveCommonAffix = 0x08; - -// Pushes the weights and/or labels of the input FST into the output mutable FST -// by pushing weights and/or labels (as determined by the ptype argument) -// towards the initial state or final states (as determined by the rtype -// template parameter). The weight type must be left distributive when pushing -// weights towards the initial state, and right distribution when pushing -// weights towards the final states. -template -void Push(const Fst &ifst, MutableFst *ofst, uint8_t ptype, - float delta = kShortestDelta) { - using Label = typename Arc::Label; - using Weight = typename Arc::Weight; - if ((ptype & (kPushWeights | kPushLabels)) == kPushWeights) { - *ofst = ifst; - Push(ofst, rtype, delta, ptype & kPushRemoveTotalWeight); - } else if (ptype & kPushLabels) { - const auto gtype = - rtype == REWEIGHT_TO_INITIAL ? GALLIC_LEFT : GALLIC_RIGHT; - using GallicWeight = typename GallicArc::Weight; - std::vector gdistance; - VectorFst> gfst; - ArcMap(ifst, &gfst, ToGallicMapper()); - if (ptype & kPushWeights) { - ShortestDistance(gfst, &gdistance, rtype == REWEIGHT_TO_INITIAL, delta); - } else { - ArcMapFst uwfst(ifst, RmWeightMapper()); - ArcMapFst guwfst(uwfst, ToGallicMapper()); - ShortestDistance(guwfst, &gdistance, rtype == REWEIGHT_TO_INITIAL, delta); - } - auto total_weight = GallicWeight::One(); - if (ptype & (kPushRemoveTotalWeight | kPushRemoveCommonAffix)) { - total_weight = - ComputeTotalWeight(gfst, gdistance, rtype == REWEIGHT_TO_INITIAL); - total_weight = GallicWeight( - ptype & kPushRemoveCommonAffix - ? total_weight.Value1() - : StringWeight::One(), - ptype & kPushRemoveTotalWeight ? total_weight.Value2() - : Weight::One()); - } - Reweight(&gfst, gdistance, rtype); - if (ptype & (kPushRemoveTotalWeight | kPushRemoveCommonAffix)) { - RemoveWeight(&gfst, total_weight, rtype == REWEIGHT_TO_FINAL); - } - FactorWeightFst, GallicFactor> - fwfst(gfst); - ArcMap(fwfst, ofst, FromGallicMapper()); - ofst->SetOutputSymbols(ifst.OutputSymbols()); - } else { - LOG(WARNING) << "Push: pushing type is set to 0, so not pushing"; - *ofst = ifst; - } -} - -} // namespace fst - -#endif // FST_PUSH_H_ diff --git a/contrib/fstlib/fst/queue.h b/contrib/fstlib/fst/queue.h deleted file mode 100644 index 8353869..0000000 --- a/contrib/fstlib/fst/queue.h +++ /dev/null @@ -1,1017 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes for various FST state queues with a unified interface. - -#ifndef FST_QUEUE_H_ -#define FST_QUEUE_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// The Queue interface is: -// -// template -// class Queue { -// public: -// using StateId = S; -// -// // Constructor: may need args (e.g., FST, comparator) for some queues. -// Queue(...) override; -// -// // Returns the head of the queue. -// StateId Head() const override; -// -// // Inserts a state. -// void Enqueue(StateId s) override; -// -// // Removes the head of the queue. -// void Dequeue() override; -// -// // Updates ordering of state s when weight changes, if necessary. -// void Update(StateId s) override; -// -// // Is the queue empty? -// bool Empty() const override; -// -// // Removes all states from the queue. -// void Clear() override; -// }; - -// State queue types. -enum QueueType { - TRIVIAL_QUEUE = 0, // Single state queue. - FIFO_QUEUE = 1, // First-in, first-out queue. - LIFO_QUEUE = 2, // Last-in, first-out queue. - SHORTEST_FIRST_QUEUE = 3, // Shortest-first queue. - TOP_ORDER_QUEUE = 4, // Topologically-ordered queue. - STATE_ORDER_QUEUE = 5, // State ID-ordered queue. - SCC_QUEUE = 6, // Component graph top-ordered meta-queue. - AUTO_QUEUE = 7, // Auto-selected queue. - OTHER_QUEUE = 8 -}; - -// QueueBase, templated on the StateId, is a virtual base class shared by all -// queues considered by AutoQueue. -template -class QueueBase { - public: - using StateId = S; - - virtual ~QueueBase() = default; - - // Concrete implementation. - - explicit QueueBase(QueueType type) : queue_type_(type), error_(false) {} - - void SetError(bool error) { error_ = error; } - - bool Error() const { return error_; } - - QueueType Type() const { return queue_type_; } - - // Virtual interface. - - virtual StateId Head() const = 0; - virtual void Enqueue(StateId) = 0; - virtual void Dequeue() = 0; - virtual void Update(StateId) = 0; - virtual bool Empty() const = 0; - virtual void Clear() = 0; - - private: - QueueType queue_type_; - bool error_; -}; - -// Trivial queue discipline; one may enqueue at most one state at a time. It -// can be used for strongly connected components with only one state and no -// self-loops. -template -class TrivialQueue : public QueueBase { - public: - using StateId = S; - - TrivialQueue() : QueueBase(TRIVIAL_QUEUE), front_(kNoStateId) {} - - ~TrivialQueue() override = default; - - StateId Head() const final { return front_; } - - void Enqueue(StateId s) final { front_ = s; } - - void Dequeue() final { front_ = kNoStateId; } - - void Update(StateId) final {} - - bool Empty() const final { return front_ == kNoStateId; } - - void Clear() final { front_ = kNoStateId; } - - private: - StateId front_; -}; - -// First-in, first-out queue discipline. -// -// This is not a final class. -template -class FifoQueue : public QueueBase { - public: - using StateId = S; - - FifoQueue() : QueueBase(FIFO_QUEUE) {} - - ~FifoQueue() override = default; - - StateId Head() const override { return queue_.front(); } - - void Enqueue(StateId s) override { queue_.push(s); } - - void Dequeue() override { queue_.pop(); } - - void Update(StateId) override {} - - bool Empty() const override { return queue_.empty(); } - - void Clear() override { queue_ = std::queue(); } - - private: - std::queue queue_; -}; - -// Last-in, first-out queue discipline. -template -class LifoQueue : public QueueBase { - public: - using StateId = S; - - LifoQueue() : QueueBase(LIFO_QUEUE) {} - - ~LifoQueue() override = default; - - StateId Head() const final { return stack_.back(); } - - void Enqueue(StateId s) final { stack_.push_back(s); } - - void Dequeue() final { stack_.pop_back(); } - - void Update(StateId) final {} - - bool Empty() const final { return stack_.empty(); } - - void Clear() final { stack_.clear(); } - - private: - std::vector stack_; -}; - -// Shortest-first queue discipline, templated on the StateId and as well as a -// comparison functor used to compare two StateIds. If a (single) state's order -// changes, it can be reordered in the queue with a call to Update(). If update -// is false, call to Update() does not reorder the queue. -// -// This is not a final class. -template -class ShortestFirstQueue : public QueueBase { - public: - using StateId = S; - - explicit ShortestFirstQueue(Compare comp) - : QueueBase(SHORTEST_FIRST_QUEUE), heap_(comp) {} - - ~ShortestFirstQueue() override = default; - - StateId Head() const override { return heap_.Top(); } - - void Enqueue(StateId s) override { - if (update) { - for (StateId i = key_.size(); i <= s; ++i) key_.push_back(kNoStateId); - key_[s] = heap_.Insert(s); - } else { - heap_.Insert(s); - } - } - - void Dequeue() override { - if (update) { - key_[heap_.Pop()] = kNoStateId; - } else { - heap_.Pop(); - } - } - - void Update(StateId s) override { - if (!update) return; - if (s >= key_.size() || key_[s] == kNoStateId) { - Enqueue(s); - } else { - heap_.Update(key_[s], s); - } - } - - bool Empty() const override { return heap_.Empty(); } - - void Clear() override { - heap_.Clear(); - if (update) key_.clear(); - } - - ssize_t Size() const { return heap_.Size(); } - - const Compare &GetCompare() const { return heap_.GetCompare(); } - - private: - Heap heap_; - std::vector key_; -}; - -namespace internal { - -// Given a vector that maps from states to weights, and a comparison functor -// for weights, this class defines a comparison function object between states. -template -class StateWeightCompare { - public: - using Weight = typename Less::Weight; - - StateWeightCompare(const std::vector &weights, const Less &less) - : weights_(weights), less_(less) {} - - bool operator()(const StateId s1, const StateId s2) const { - return less_(weights_[s1], weights_[s2]); - } - - private: - // Borrowed references. - const std::vector &weights_; - const Less &less_; -}; - -// Comparison that can never be instantiated. Useful only to pass a pointer to -// this to a function that needs a comparison when it is known that the pointer -// will always be null. -template -struct ErrorLess { - using Weight = W; - ErrorLess() { - FSTERROR() << "ErrorLess: instantiated for Weight " << Weight::Type(); - } - bool operator()(const Weight &, const Weight &) const { return false; } -}; - -} // namespace internal - -// Shortest-first queue discipline, templated on the StateId and Weight, is -// specialized to use the weight's natural order for the comparison function. -// Requires Weight is idempotent (due to use of NaturalLess). -template -class NaturalShortestFirstQueue - : public ShortestFirstQueue< - S, internal::StateWeightCompare>> { - public: - using StateId = S; - using Less = NaturalLess; - using Compare = internal::StateWeightCompare; - - explicit NaturalShortestFirstQueue(const std::vector &distance) - : ShortestFirstQueue(Compare(distance, Less())) {} - - ~NaturalShortestFirstQueue() override = default; -}; - -// In a shortest path computation on a lattice-like FST, we may keep many old -// nonviable paths as a part of the search. Since the search process always -// expands the lowest cost path next, that lowest cost path may be a very old -// nonviable path instead of one we expect to lead to a shortest path. -// -// For instance, suppose that the current best path in an alignment has -// traversed 500 arcs with a cost of 10. We may also have a bad path in -// the queue that has traversed only 40 arcs but also has a cost of 10. -// This path is very unlikely to lead to a reasonable alignment, so this queue -// can prune it from the search space. -// -// This queue relies on the caller using a shortest-first exploration order -// like this: -// while (true) { -// StateId head = queue.Head(); -// queue.Dequeue(); -// for (const auto& arc : GetArcs(fst, head)) { -// queue.Enqueue(arc.nextstate); -// } -// } -// We use this assumption to guess that there is an arc between Head and the -// Enqueued state; this is how the number of path steps is measured. -template -class PruneNaturalShortestFirstQueue - : public NaturalShortestFirstQueue { - public: - using StateId = S; - using Base = NaturalShortestFirstQueue; - - PruneNaturalShortestFirstQueue(const std::vector &distance, - ssize_t arc_threshold, ssize_t state_limit = 0) - : Base(distance), - arc_threshold_(arc_threshold), - state_limit_(state_limit), - head_steps_(0), - max_head_steps_(0) {} - - ~PruneNaturalShortestFirstQueue() override = default; - - StateId Head() const override { - const auto head = Base::Head(); - // Stores the number of steps from the start of the graph to this state - // along the shortest-weight path. - if (head < steps_.size()) { - max_head_steps_ = std::max(steps_[head], max_head_steps_); - head_steps_ = steps_[head]; - } - return head; - } - - void Enqueue(StateId s) override { - // We assume that there is an arc between the Head() state and this - // Enqueued state. - const ssize_t state_steps = head_steps_ + 1; - if (s >= steps_.size()) { - steps_.resize(s + 1, state_steps); - } - // This is the number of arcs in the minimum cost path from Start to s. - steps_[s] = state_steps; - - // Adjust the threshold in cases where path step thresholding wasn't - // enough to keep the queue small. - ssize_t adjusted_threshold = arc_threshold_; - if (Base::Size() > state_limit_ && state_limit_ > 0) { - adjusted_threshold = std::max( - 0, arc_threshold_ - (Base::Size() / state_limit_) - 1); - } - - if (state_steps > (max_head_steps_ - adjusted_threshold) || - arc_threshold_ < 0) { - if (adjusted_threshold == 0 && state_limit_ > 0) { - // If the queue is continuing to grow without bound, we follow any - // path that makes progress and clear the rest. - Base::Clear(); - } - Base::Enqueue(s); - } - } - - private: - // A dense map from StateId to the number of arcs in the minimum weight - // path from Start to this state. - std::vector steps_; - // We only keep paths that are within this number of arcs (not weight!) - // of the longest path. - const ssize_t arc_threshold_; - // If the size of the queue climbs above this number, we increase the - // threshold to reduce the amount of work we have to do. - const ssize_t state_limit_; - - // The following are mutable because Head() is const. - // The number of arcs traversed in the minimum cost path from the start - // state to the current Head() state. - mutable ssize_t head_steps_; - // The maximum number of arcs traversed by any low-cost path so far. - mutable ssize_t max_head_steps_; -}; - -// Topological-order queue discipline, templated on the StateId. States are -// ordered in the queue topologically. The FST must be acyclic. -template -class TopOrderQueue : public QueueBase { - public: - using StateId = S; - - // This constructor computes the topological order. It accepts an arc filter - // to limit the transitions considered in that computation (e.g., only the - // epsilon graph). - template - TopOrderQueue(const Fst &fst, ArcFilter filter) - : QueueBase(TOP_ORDER_QUEUE), - front_(0), - back_(kNoStateId), - order_(0), - state_(0) { - bool acyclic; - TopOrderVisitor top_order_visitor(&order_, &acyclic); - DfsVisit(fst, &top_order_visitor, filter); - if (!acyclic) { - FSTERROR() << "TopOrderQueue: FST is not acyclic"; - QueueBase::SetError(true); - } - state_.resize(order_.size(), kNoStateId); - } - - // This constructor is passed the pre-computed topological order. - explicit TopOrderQueue(const std::vector &order) - : QueueBase(TOP_ORDER_QUEUE), - front_(0), - back_(kNoStateId), - order_(order), - state_(order.size(), kNoStateId) {} - - ~TopOrderQueue() override = default; - - StateId Head() const final { return state_[front_]; } - - void Enqueue(StateId s) final { - if (front_ > back_) { - front_ = back_ = order_[s]; - } else if (order_[s] > back_) { - back_ = order_[s]; - } else if (order_[s] < front_) { - front_ = order_[s]; - } - state_[order_[s]] = s; - } - - void Dequeue() final { - state_[front_] = kNoStateId; - while ((front_ <= back_) && (state_[front_] == kNoStateId)) ++front_; - } - - void Update(StateId) final {} - - bool Empty() const final { return front_ > back_; } - - void Clear() final { - for (StateId s = front_; s <= back_; ++s) state_[s] = kNoStateId; - back_ = kNoStateId; - front_ = 0; - } - - private: - StateId front_; - StateId back_; - std::vector order_; - std::vector state_; -}; - -// State order queue discipline, templated on the StateId. States are ordered in -// the queue by state ID. -template -class StateOrderQueue : public QueueBase { - public: - using StateId = S; - - StateOrderQueue() - : QueueBase(STATE_ORDER_QUEUE), front_(0), back_(kNoStateId) {} - - ~StateOrderQueue() override = default; - - StateId Head() const final { return front_; } - - void Enqueue(StateId s) final { - if (front_ > back_) { - front_ = back_ = s; - } else if (s > back_) { - back_ = s; - } else if (s < front_) { - front_ = s; - } - while (enqueued_.size() <= s) enqueued_.push_back(false); - enqueued_[s] = true; - } - - void Dequeue() final { - enqueued_[front_] = false; - while ((front_ <= back_) && (enqueued_[front_] == false)) ++front_; - } - - void Update(StateId) final {} - - bool Empty() const final { return front_ > back_; } - - void Clear() final { - for (StateId i = front_; i <= back_; ++i) enqueued_[i] = false; - front_ = 0; - back_ = kNoStateId; - } - - private: - StateId front_; - StateId back_; - std::vector enqueued_; -}; - -// SCC topological-order meta-queue discipline, templated on the StateId and a -// queue used inside each SCC. It visits the SCCs of an FST in topological -// order. Its constructor is passed the queues to to use within an SCC. -template -class SccQueue : public QueueBase { - public: - using StateId = S; - - // Constructor takes a vector specifying the SCC number per state and a - // vector giving the queue to use per SCC number. - SccQueue(const std::vector &scc, - std::vector> *queue) - : QueueBase(SCC_QUEUE), - queue_(queue), - scc_(scc), - front_(0), - back_(kNoStateId) {} - - ~SccQueue() override = default; - - StateId Head() const final { - while ((front_ <= back_) && - (((*queue_)[front_] && (*queue_)[front_]->Empty()) || - (((*queue_)[front_] == nullptr) && - ((front_ >= trivial_queue_.size()) || - (trivial_queue_[front_] == kNoStateId))))) { - ++front_; - } - if ((*queue_)[front_]) { - return (*queue_)[front_]->Head(); - } else { - return trivial_queue_[front_]; - } - } - - void Enqueue(StateId s) final { - if (front_ > back_) { - front_ = back_ = scc_[s]; - } else if (scc_[s] > back_) { - back_ = scc_[s]; - } else if (scc_[s] < front_) { - front_ = scc_[s]; - } - if ((*queue_)[scc_[s]]) { - (*queue_)[scc_[s]]->Enqueue(s); - } else { - while (trivial_queue_.size() <= scc_[s]) { - trivial_queue_.push_back(kNoStateId); - } - trivial_queue_[scc_[s]] = s; - } - } - - void Dequeue() final { - if ((*queue_)[front_]) { - (*queue_)[front_]->Dequeue(); - } else if (front_ < trivial_queue_.size()) { - trivial_queue_[front_] = kNoStateId; - } - } - - void Update(StateId s) final { - if ((*queue_)[scc_[s]]) (*queue_)[scc_[s]]->Update(s); - } - - bool Empty() const final { - // Queues SCC number back_ is not empty unless back_ == front_. - if (front_ < back_) { - return false; - } else if (front_ > back_) { - return true; - } else if ((*queue_)[front_]) { - return (*queue_)[front_]->Empty(); - } else { - return (front_ >= trivial_queue_.size()) || - (trivial_queue_[front_] == kNoStateId); - } - } - - void Clear() final { - for (StateId i = front_; i <= back_; ++i) { - if ((*queue_)[i]) { - (*queue_)[i]->Clear(); - } else if (i < trivial_queue_.size()) { - trivial_queue_[i] = kNoStateId; - } - } - front_ = 0; - back_ = kNoStateId; - } - - private: - std::vector> *queue_; - const std::vector &scc_; - mutable StateId front_; - StateId back_; - std::vector trivial_queue_; -}; - -// Automatic queue discipline. It selects a queue discipline for a given FST -// based on its properties. -template -class AutoQueue : public QueueBase { - public: - using StateId = S; - - // This constructor takes a state distance vector that, if non-null and if - // the Weight type has the path property, will entertain the shortest-first - // queue using the natural order w.r.t to the distance. - template - AutoQueue(const Fst &fst, - const std::vector *distance, ArcFilter filter) - : QueueBase(AUTO_QUEUE) { - using Weight = typename Arc::Weight; - // We need to have variables of type Less and Compare, so we use - // ErrorLess if the type NaturalLess cannot be instantiated due - // to lack of path property. - using Less = std::conditional_t::value, NaturalLess, - internal::ErrorLess>; - using Compare = internal::StateWeightCompare; - // First checks if the FST is known to have these properties. - const auto props = - fst.Properties(kAcyclic | kCyclic | kTopSorted | kUnweighted, false); - if ((props & kTopSorted) || fst.Start() == kNoStateId) { - queue_ = std::make_unique>(); - VLOG(2) << "AutoQueue: using state-order discipline"; - } else if (props & kAcyclic) { - queue_ = std::make_unique>(fst, filter); - VLOG(2) << "AutoQueue: using top-order discipline"; - } else if ((props & kUnweighted) && IsIdempotent::value) { - queue_ = std::make_unique>(); - VLOG(2) << "AutoQueue: using LIFO discipline"; - } else { - uint64_t properties; - // Decomposes into strongly-connected components. - SccVisitor scc_visitor(&scc_, nullptr, nullptr, &properties); - DfsVisit(fst, &scc_visitor, filter); - auto nscc = *std::max_element(scc_.begin(), scc_.end()) + 1; - std::vector queue_types(nscc); - std::unique_ptr less; - std::unique_ptr comp; - if constexpr (IsPath::value) { - if (distance) { - less = std::make_unique(); - comp = std::make_unique(*distance, *less); - } - } - // Finds the queue type to use per SCC. - bool unweighted; - bool all_trivial; - SccQueueType(fst, scc_, &queue_types, filter, less.get(), &all_trivial, - &unweighted); - // If unweighted and semiring is idempotent, uses LIFO queue. - if (unweighted) { - queue_ = std::make_unique>(); - VLOG(2) << "AutoQueue: using LIFO discipline"; - return; - } - // If all the SCC are trivial, the FST is acyclic and the scc number gives - // the topological order. - if (all_trivial) { - queue_ = std::make_unique>(scc_); - VLOG(2) << "AutoQueue: using top-order discipline"; - return; - } - VLOG(2) << "AutoQueue: using SCC meta-discipline"; - queues_.resize(nscc); - for (StateId i = 0; i < nscc; ++i) { - switch (queue_types[i]) { - case TRIVIAL_QUEUE: - queues_[i].reset(); - VLOG(3) << "AutoQueue: SCC #" << i << ": using trivial discipline"; - break; - case SHORTEST_FIRST_QUEUE: - // The IsPath test is not needed for correctness. It just saves - // instantiating a ShortestFirstQueue that can never be called. - if constexpr (IsPath::value) { - queues_[i] = - std::make_unique>( - *comp); - VLOG(3) << "AutoQueue: SCC #" << i - << ": using shortest-first discipline"; - } else { - // SccQueueType should ensure this can never happen. - FSTERROR() << "Got SHORTEST_FIRST_QUEUE for non-Path Weight " - << Weight::Type(); - queues_[i].reset(); - } - break; - case LIFO_QUEUE: - queues_[i] = std::make_unique>(); - VLOG(3) << "AutoQueue: SCC #" << i << ": using LIFO discipline"; - break; - case FIFO_QUEUE: - default: - queues_[i] = std::make_unique>(); - VLOG(3) << "AutoQueue: SCC #" << i << ": using FIFO discipine"; - break; - } - } - queue_ = std::make_unique>>( - scc_, &queues_); - } - } - - ~AutoQueue() override = default; - - StateId Head() const final { return queue_->Head(); } - - void Enqueue(StateId s) final { queue_->Enqueue(s); } - - void Dequeue() final { queue_->Dequeue(); } - - void Update(StateId s) final { queue_->Update(s); } - - bool Empty() const final { return queue_->Empty(); } - - void Clear() final { queue_->Clear(); } - - private: - template - static void SccQueueType(const Fst &fst, const std::vector &scc, - std::vector *queue_types, - ArcFilter filter, Less *less, bool *all_trivial, - bool *unweighted); - - std::unique_ptr> queue_; - std::vector>> queues_; - std::vector scc_; -}; - -// Examines the states in an FST's strongly connected components and determines -// which type of queue to use per SCC. Stores result as a vector of QueueTypes -// which is assumed to have length equal to the number of SCCs. An arc filter -// is used to limit the transitions considered (e.g., only the epsilon graph). -// The argument all_trivial is set to true if every queue is the trivial queue. -// The argument unweighted is set to true if the semiring is idempotent and all -// the arc weights are equal to Zero() or One(). -template -template -void AutoQueue::SccQueueType(const Fst &fst, - const std::vector &scc, - std::vector *queue_type, - ArcFilter filter, Less *less, - bool *all_trivial, bool *unweighted) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - *all_trivial = true; - *unweighted = true; - for (StateId i = 0; i < queue_type->size(); ++i) { - (*queue_type)[i] = TRIVIAL_QUEUE; - } - for (StateIterator> sit(fst); !sit.Done(); sit.Next()) { - const auto state = sit.Value(); - for (ArcIterator> ait(fst, state); !ait.Done(); ait.Next()) { - const auto &arc = ait.Value(); - if (!filter(arc)) continue; - if (scc[state] == scc[arc.nextstate]) { - auto &type = (*queue_type)[scc[state]]; - if constexpr (!IsPath::value) { - type = FIFO_QUEUE; - } else if (!less || (*less)(arc.weight, Weight::One())) { - type = FIFO_QUEUE; - } else if ((type == TRIVIAL_QUEUE) || (type == LIFO_QUEUE)) { - if (!IsIdempotent::value || - (arc.weight != Weight::Zero() && arc.weight != Weight::One())) { - type = SHORTEST_FIRST_QUEUE; - } else { - type = LIFO_QUEUE; - } - } - if (type != TRIVIAL_QUEUE) *all_trivial = false; - } - if (!IsIdempotent::value || - (arc.weight != Weight::Zero() && arc.weight != Weight::One())) { - *unweighted = false; - } - } - } -} - -// An A* estimate is a function object that maps from a state ID to an -// estimate of the shortest distance to the final states. - -// A trivial A* estimate, yielding a queue which behaves the same in Dijkstra's -// algorithm. -template -struct TrivialAStarEstimate { - constexpr Weight operator()(StateId) const { return Weight::One(); } -}; - -// A non-trivial A* estimate using a vector of the estimated future costs. -template -class NaturalAStarEstimate { - public: - NaturalAStarEstimate(const std::vector &beta) : beta_(beta) {} - - const Weight &operator()(StateId s) const { - return (s < beta_.size()) ? beta_[s] : kZero; - } - - private: - static constexpr Weight kZero = Weight::Zero(); - - const std::vector &beta_; -}; - -// Given a vector that maps from states to weights representing the shortest -// distance from the initial state, a comparison function object between -// weights, and an estimate of the shortest distance to the final states, this -// class defines a comparison function object between states. -template -class AStarWeightCompare { - public: - using StateId = S; - using Weight = typename Less::Weight; - - AStarWeightCompare(const std::vector &weights, const Less &less, - const Estimate &estimate) - : weights_(weights), less_(less), estimate_(estimate) {} - - bool operator()(StateId s1, StateId s2) const { - const auto w1 = Times(weights_[s1], estimate_(s1)); - const auto w2 = Times(weights_[s2], estimate_(s2)); - return less_(w1, w2); - } - - const Estimate &GetEstimate() const { return estimate_; } - - private: - const std::vector &weights_; - const Less &less_; - const Estimate &estimate_; -}; - -// A* queue discipline templated on StateId, Weight, and Estimate. -template -class NaturalAStarQueue - : public ShortestFirstQueue< - S, AStarWeightCompare, Estimate>> { - public: - using StateId = S; - using Compare = AStarWeightCompare, Estimate>; - - NaturalAStarQueue(const std::vector &distance, - const Estimate &estimate) - : ShortestFirstQueue( - Compare(distance, less_, estimate)) {} - - ~NaturalAStarQueue() override = default; - - private: - // This is non-static because the constructor for non-idempotent weights will - // result in an error. - const NaturalLess less_{}; -}; - -// A state equivalence class is a function object that maps from a state ID to -// an equivalence class (state) ID. The trivial equivalence class maps a state -// ID to itself. -template -struct TrivialStateEquivClass { - StateId operator()(StateId s) const { return s; } -}; - -// Distance-based pruning queue discipline: Enqueues a state only when its -// shortest distance (so far), as specified by distance, is less than (as -// specified by comp) the shortest distance Times() the threshold to any state -// in the same equivalence class, as specified by the functor class_func. The -// underlying queue discipline is specified by queue. -// -// This is not a final class. -template -class PruneQueue : public QueueBase { - public: - using StateId = typename Queue::StateId; - using Weight = typename Less::Weight; - - PruneQueue(const std::vector &distance, std::unique_ptr queue, - const Less &less, const ClassFnc &class_fnc, Weight threshold) - : QueueBase(OTHER_QUEUE), - distance_(distance), - queue_(std::move(queue)), - less_(less), - class_fnc_(class_fnc), - threshold_(std::move(threshold)) {} - - ~PruneQueue() override = default; - - StateId Head() const override { return queue_->Head(); } - - void Enqueue(StateId s) override { - const auto c = class_fnc_(s); - if (c >= class_distance_.size()) { - class_distance_.resize(c + 1, Weight::Zero()); - } - if (less_(distance_[s], class_distance_[c])) { - class_distance_[c] = distance_[s]; - } - // Enqueues only if below threshold limit. - const auto limit = Times(class_distance_[c], threshold_); - if (less_(distance_[s], limit)) queue_->Enqueue(s); - } - - void Dequeue() override { queue_->Dequeue(); } - - void Update(StateId s) override { - const auto c = class_fnc_(s); - if (less_(distance_[s], class_distance_[c])) { - class_distance_[c] = distance_[s]; - } - queue_->Update(s); - } - - bool Empty() const override { return queue_->Empty(); } - - void Clear() override { queue_->Clear(); } - - private: - const std::vector &distance_; // Shortest distance to state. - std::unique_ptr queue_; - const Less &less_; // Borrowed reference. - const ClassFnc &class_fnc_; // Equivalence class functor. - Weight threshold_; // Pruning weight threshold. - std::vector class_distance_; // Shortest distance to class. -}; - -// Pruning queue discipline (see above) using the weight's natural order for the -// comparison function. The ownership of the queue argument is given to this -// class. -template -class NaturalPruneQueue final - : public PruneQueue, ClassFnc> { - public: - using StateId = typename Queue::StateId; - - NaturalPruneQueue(const std::vector &distance, - std::unique_ptr queue, const ClassFnc &class_fnc, - Weight threshold) - : PruneQueue, ClassFnc>( - distance, std::move(queue), NaturalLess(), class_fnc, - threshold) {} - - ~NaturalPruneQueue() override = default; -}; - -// Filter-based pruning queue discipline: enqueues a state only if allowed by -// the filter, specified by the state filter functor argument. The underlying -// queue discipline is specified by the queue argument. -template -class FilterQueue : public QueueBase { - public: - using StateId = typename Queue::StateId; - - FilterQueue(std::unique_ptr queue, const Filter &filter) - : QueueBase(OTHER_QUEUE), - queue_(std::move(queue)), - filter_(filter) {} - - ~FilterQueue() override = default; - - StateId Head() const final { return queue_->Head(); } - - // Enqueues only if allowed by state filter. - void Enqueue(StateId s) final { - if (filter_(s)) queue_->Enqueue(s); - } - - void Dequeue() final { queue_->Dequeue(); } - - void Update(StateId s) final {} - - bool Empty() const final { return queue_->Empty(); } - - void Clear() final { queue_->Clear(); } - - private: - std::unique_ptr queue_; - const Filter &filter_; -}; - -} // namespace fst - -#endif // FST_QUEUE_H_ diff --git a/contrib/fstlib/fst/randequivalent.h b/contrib/fstlib/fst/randequivalent.h deleted file mode 100644 index f117e98..0000000 --- a/contrib/fstlib/fst/randequivalent.h +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Tests if two FSTS are equivalent by checking if random strings from one FST -// are transduced the same by both FSTs. - -#ifndef FST_RANDEQUIVALENT_H_ -#define FST_RANDEQUIVALENT_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Test if two FSTs are stochastically equivalent by randomly generating -// random paths through the FSTs. -// -// For each randomly generated path, the algorithm computes for each -// of the two FSTs the sum of the weights of all the successful paths -// sharing the same input and output labels as the considered randomly -// generated path and checks that these two values are within a user-specified -// delta. Returns optional error value (when FST_FLAGS_error_fatal = false). -template -bool RandEquivalent(const Fst &fst1, const Fst &fst2, int32_t npath, - const RandGenOptions &opts, - float delta = kDelta, - uint64_t seed = std::random_device()(), - bool *error = nullptr) { - using Weight = typename Arc::Weight; - if (error) *error = false; - // Checks that the symbol table are compatible. - if (!CompatSymbols(fst1.InputSymbols(), fst2.InputSymbols()) || - !CompatSymbols(fst1.OutputSymbols(), fst2.OutputSymbols())) { - FSTERROR() << "RandEquivalent: Input/output symbol tables of 1st " - << "argument do not match input/output symbol tables of 2nd " - << "argument"; - if (error) *error = true; - return false; - } - static const ILabelCompare icomp; - static const OLabelCompare ocomp; - VectorFst sfst1(fst1); - VectorFst sfst2(fst2); - Connect(&sfst1); - Connect(&sfst2); - ArcSort(&sfst1, icomp); - ArcSort(&sfst2, icomp); - bool result = true; - std::mt19937 rand(seed); - std::bernoulli_distribution coin(.5); - for (int32_t n = 0; n < npath; ++n) { - VectorFst path; - const auto &fst = coin(rand) ? sfst1 : sfst2; - RandGen(fst, &path, opts); - VectorFst ipath(path); - VectorFst opath(path); - Project(&ipath, ProjectType::INPUT); - Project(&opath, ProjectType::OUTPUT); - VectorFst cfst1, pfst1; - Compose(ipath, sfst1, &cfst1); - ArcSort(&cfst1, ocomp); - Compose(cfst1, opath, &pfst1); - // Gives up if there are epsilon cycles in a non-idempotent semiring. - if (!IsIdempotent::value && pfst1.Properties(kCyclic, true)) { - continue; - } - const auto sum1 = ShortestDistance(pfst1); - VectorFst cfst2; - Compose(ipath, sfst2, &cfst2); - ArcSort(&cfst2, ocomp); - VectorFst pfst2; - Compose(cfst2, opath, &pfst2); - // Gives up if there are epsilon cycles in a non-idempotent semiring. - if (!IsIdempotent::value && pfst2.Properties(kCyclic, true)) { - continue; - } - const auto sum2 = ShortestDistance(pfst2); - if (!ApproxEqual(sum1, sum2, delta)) { - VLOG(1) << "Sum1 = " << sum1; - VLOG(1) << "Sum2 = " << sum2; - result = false; - break; - } - } - if (fst1.Properties(kError, false) || fst2.Properties(kError, false)) { - if (error) *error = true; - return false; - } - return result; -} - -// Tests if two FSTs are equivalent by randomly generating a nnpath paths -// (no longer than the path_length) using a user-specified seed, optionally -// indicating an error setting an optional error argument to true. -template -bool RandEquivalent(const Fst &fst1, const Fst &fst2, int32_t npath, - float delta = kDelta, - uint64_t seed = std::random_device()(), - int32_t max_length = std::numeric_limits::max(), - bool *error = nullptr) { - const UniformArcSelector uniform_selector(seed); - const RandGenOptions> opts(uniform_selector, - max_length); - return RandEquivalent(fst1, fst2, npath, opts, delta, seed, error); -} - -} // namespace fst - -#endif // FST_RANDEQUIVALENT_H_ diff --git a/contrib/fstlib/fst/randgen.h b/contrib/fstlib/fst/randgen.h deleted file mode 100644 index 8dd92d2..0000000 --- a/contrib/fstlib/fst/randgen.h +++ /dev/null @@ -1,780 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes and functions to generate random paths through an FST. - -#ifndef FST_RANDGEN_H_ -#define FST_RANDGEN_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// The RandGenFst class is roughly similar to ArcMapFst in that it takes two -// template parameters denoting the input and output arc types. However, it also -// takes an additional template parameter which specifies a sampler object which -// samples (with replacement) arcs from an FST state. The sampler in turn takes -// a template parameter for a selector object which actually chooses the arc. -// -// Arc selector functors are used to select a random transition given an FST -// state s, returning a number N such that 0 <= N <= NumArcs(s). If N is -// NumArcs(s), then the final weight is selected; otherwise the N-th arc is -// selected. It is assumed these are not applied to any state which is neither -// final nor has any arcs leaving it. - -// Randomly selects a transition using the uniform distribution. This class is -// not thread-safe. -template -class UniformArcSelector { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit UniformArcSelector(uint64_t seed = std::random_device()()) - : rand_(seed) {} - - size_t operator()(const Fst &fst, StateId s) const { - const auto n = fst.NumArcs(s) + (fst.Final(s) != Weight::Zero()); - return static_cast( - std::uniform_int_distribution<>(0, n - 1)(rand_)); - } - - private: - mutable std::mt19937_64 rand_; -}; - -// Randomly selects a transition w.r.t. the weights treated as negative log -// probabilities after normalizing for the total weight leaving the state. Zero -// transitions are disregarded. It assumed that Arc::Weight::Value() accesses -// the floating point representation of the weight. This class is not -// thread-safe. -template -class LogProbArcSelector { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - // Constructs a selector with a non-deterministic seed. - LogProbArcSelector() : seed_(std::random_device()()), rand_(seed_) {} - - // Constructs a selector with a given seed. - explicit LogProbArcSelector(uint64_t seed) : seed_(seed), rand_(seed) {} - - size_t operator()(const Fst &fst, StateId s) const { - // Finds total weight leaving state. - auto sum = Log64Weight::Zero(); - ArcIterator> aiter(fst, s); - for (; !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - sum = Plus(sum, to_log_weight_(arc.weight)); - } - sum = Plus(sum, to_log_weight_(fst.Final(s))); - const double threshold = - std::uniform_real_distribution<>(0, exp(-sum.Value()))(rand_); - auto p = Log64Weight::Zero(); - size_t n = 0; - for (aiter.Reset(); !aiter.Done(); aiter.Next(), ++n) { - p = Plus(p, to_log_weight_(aiter.Value().weight)); - if (exp(-p.Value()) > threshold) return n; - } - return n; - } - - uint64_t Seed() const { return seed_; } - - protected: - Log64Weight ToLogWeight(const Weight &weight) const { - return to_log_weight_(weight); - } - - std::mt19937_64 &MutableRand() const { return rand_; } - - private: - const uint64_t seed_; - mutable std::mt19937_64 rand_; - const WeightConvert to_log_weight_{}; -}; - -// Same as LogProbArcSelector but use CacheLogAccumulator to cache the weight -// accumulation computations. This class is not thread-safe. -template -class FastLogProbArcSelector : public LogProbArcSelector { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using LogProbArcSelector::MutableRand; - using LogProbArcSelector::ToLogWeight; - using LogProbArcSelector::operator(); - - // Constructs a selector with a non-deterministic seed. - FastLogProbArcSelector() : LogProbArcSelector() {} - // Constructs a selector with a given seed. - explicit FastLogProbArcSelector(uint64_t seed) - : LogProbArcSelector(seed) {} - - size_t operator()(const Fst &fst, StateId s, - CacheLogAccumulator *accumulator) const { - accumulator->SetState(s); - ArcIterator> aiter(fst, s); - // Finds total weight leaving state. - const double sum = - ToLogWeight(accumulator->Sum(fst.Final(s), &aiter, 0, fst.NumArcs(s))) - .Value(); - const double r = - -log(std::uniform_real_distribution<>(0, 1)(MutableRand())); - Weight w = from_log_weight_(r + sum); - aiter.Reset(); - return accumulator->LowerBound(w, &aiter); - } - - private: - const WeightConvert from_log_weight_{}; -}; - -// Random path state info maintained by RandGenFst and passed to samplers. -template -struct RandState { - using StateId = typename Arc::StateId; - - StateId state_id; // Current input FST state. - size_t nsamples; // Number of samples to be sampled at this state. - size_t length; // Length of path to this random state. - size_t select; // Previous sample arc selection. - const RandState *parent; // Previous random state on this path. - - explicit RandState(StateId state_id, size_t nsamples = 0, size_t length = 0, - size_t select = 0, const RandState *parent = nullptr) - : state_id(state_id), - nsamples(nsamples), - length(length), - select(select), - parent(parent) {} - - RandState() : RandState(kNoStateId) {} -}; - -// This class, given an arc selector, samples, with replacement, multiple random -// transitions from an FST's state. This is a generic version with a -// straightforward use of the arc selector. Specializations may be defined for -// arc selectors for greater efficiency or special behavior. -template -class ArcSampler { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - // The max_length argument may be interpreted (or ignored) by a selector as - // it chooses. This generic version interprets this literally. - ArcSampler(const Fst &fst, const Selector &selector, - int32_t max_length = std::numeric_limits::max()) - : fst_(fst), selector_(selector), max_length_(max_length) {} - - // Allow updating FST argument; pass only if changed. - ArcSampler(const ArcSampler &sampler, - const Fst *fst = nullptr) - : fst_(fst ? *fst : sampler.fst_), - selector_(sampler.selector_), - max_length_(sampler.max_length_) { - Reset(); - } - - // Samples a fixed number of samples from the given state. The length argument - // specifies the length of the path to the state. Returns true if the samples - // were collected. No samples may be collected if either there are no - // transitions leaving the state and the state is non-final, or if the path - // length has been exceeded. Iterator members are provided to read the samples - // in the order in which they were collected. - bool Sample(const RandState &rstate) { - sample_map_.clear(); - if ((fst_.NumArcs(rstate.state_id) == 0 && - fst_.Final(rstate.state_id) == Weight::Zero()) || - rstate.length == max_length_) { - Reset(); - return false; - } - for (size_t i = 0; i < rstate.nsamples; ++i) { - ++sample_map_[selector_(fst_, rstate.state_id)]; - } - Reset(); - return true; - } - - // More samples? - bool Done() const { return sample_iter_ == sample_map_.end(); } - - // Gets the next sample. - void Next() { ++sample_iter_; } - - std::pair Value() const { return *sample_iter_; } - - void Reset() { sample_iter_ = sample_map_.begin(); } - - bool Error() const { return false; } - - private: - const Fst &fst_; - const Selector &selector_; - const int32_t max_length_; - - // Stores (N, K) as described for Value(). - std::map sample_map_; - std::map::const_iterator sample_iter_; - - ArcSampler &operator=(const ArcSampler &) = delete; -}; - -// Samples one sample of num_to_sample dimensions from a multinomial -// distribution parameterized by a vector of probabilities. The result -// container should be pre-initialized (e.g., an empty map or a zeroed vector -// sized the same as the vector of probabilities. -// probs.size()). -template -void OneMultinomialSample(const std::vector &probs, - size_t num_to_sample, Result *result, RNG *rng) { - using distribution = std::binomial_distribution; - // Left-over probability mass. Keep an array of the partial sums because - // keeping a scalar and modifying norm -= probs[i] in the loop will result - // in round-off error and can have probs[i] > norm. - std::vector norm(probs.size()); - std::partial_sum(probs.rbegin(), probs.rend(), norm.rbegin()); - // Left-over number of samples needed. - for (size_t i = 0; i < probs.size(); ++i) { - distribution::result_type num_sampled = 0; - if (probs[i] > 0) { - distribution d(num_to_sample, probs[i] / norm[i]); - num_sampled = d(*rng); - } - if (num_sampled != 0) (*result)[i] = num_sampled; - num_to_sample -= std::min(num_sampled, num_to_sample); - } -} - -// Specialization for FastLogProbArcSelector. -template -class ArcSampler> { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Accumulator = CacheLogAccumulator; - using Selector = FastLogProbArcSelector; - - ArcSampler(const Fst &fst, const Selector &selector, - int32_t max_length = std::numeric_limits::max()) - : fst_(fst), - selector_(selector), - max_length_(max_length), - accumulator_(new Accumulator()) { - accumulator_->Init(fst); - rng_.seed(selector_.Seed()); - } - - ArcSampler(const ArcSampler &sampler, - const Fst *fst = nullptr) - : fst_(fst ? *fst : sampler.fst_), - selector_(sampler.selector_), - max_length_(sampler.max_length_) { - if (fst) { - accumulator_ = std::make_unique(); - accumulator_->Init(*fst); - } else { // Shallow copy. - accumulator_ = std::make_unique(*sampler.accumulator_); - } - } - - bool Sample(const RandState &rstate) { - sample_map_.clear(); - if ((fst_.NumArcs(rstate.state_id) == 0 && - fst_.Final(rstate.state_id) == Weight::Zero()) || - rstate.length == max_length_) { - Reset(); - return false; - } - if (fst_.NumArcs(rstate.state_id) + 1 < rstate.nsamples) { - MultinomialSample(rstate); - Reset(); - return true; - } - for (size_t i = 0; i < rstate.nsamples; ++i) { - ++sample_map_[selector_(fst_, rstate.state_id, accumulator_.get())]; - } - Reset(); - return true; - } - - bool Done() const { return sample_iter_ == sample_map_.end(); } - - void Next() { ++sample_iter_; } - - std::pair Value() const { return *sample_iter_; } - - void Reset() { sample_iter_ = sample_map_.begin(); } - - bool Error() const { return accumulator_->Error(); } - - private: - using RNG = std::mt19937; - - // Sample according to the multinomial distribution of rstate.nsamples draws - // from p_. - void MultinomialSample(const RandState &rstate) { - p_.clear(); - for (ArcIterator> aiter(fst_, rstate.state_id); !aiter.Done(); - aiter.Next()) { - p_.push_back(exp(-to_log_weight_(aiter.Value().weight).Value())); - } - if (fst_.Final(rstate.state_id) != Weight::Zero()) { - p_.push_back(exp(-to_log_weight_(fst_.Final(rstate.state_id)).Value())); - } - if (rstate.nsamples < std::numeric_limits::max()) { - OneMultinomialSample(p_, rstate.nsamples, &sample_map_, &rng_); - } else { - for (size_t i = 0; i < p_.size(); ++i) { - sample_map_[i] = ceil(p_[i] * rstate.nsamples); - } - } - } - - const Fst &fst_; - const Selector &selector_; - const int32_t max_length_; - - // Stores (N, K) for Value(). - std::map sample_map_; - std::map::const_iterator sample_iter_; - - std::unique_ptr accumulator_; - RNG rng_; // Random number generator. - std::vector p_; // Multinomial parameters. - const WeightConvert to_log_weight_{}; -}; - -// Options for random path generation with RandGenFst. The template argument is -// a sampler, typically the class ArcSampler. Ownership of the sampler is taken -// by RandGenFst. -template -struct RandGenFstOptions : public CacheOptions { - Sampler *sampler; // How to sample transitions at a state. - int32_t npath; // Number of paths to generate. - bool weighted; // Is the output tree weighted by path count, or - // is it just an unweighted DAG? - bool remove_total_weight; // Remove total weight when output is weighted. - - RandGenFstOptions(const CacheOptions &opts, Sampler *sampler, - int32_t npath = 1, bool weighted = true, - bool remove_total_weight = false) - : CacheOptions(opts), - sampler(sampler), - npath(npath), - weighted(weighted), - remove_total_weight(remove_total_weight) {} -}; - -namespace internal { - -// Implementation of RandGenFst. -template -class RandGenFstImpl : public CacheImpl { - public: - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheBaseImpl>::EmplaceArc; - using CacheBaseImpl>::HasArcs; - using CacheBaseImpl>::HasFinal; - using CacheBaseImpl>::HasStart; - using CacheBaseImpl>::SetArcs; - using CacheBaseImpl>::SetFinal; - using CacheBaseImpl>::SetStart; - - using Label = typename FromArc::Label; - using StateId = typename FromArc::StateId; - using FromWeight = typename FromArc::Weight; - - using ToWeight = typename ToArc::Weight; - - RandGenFstImpl(const Fst &fst, - const RandGenFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - sampler_(opts.sampler), - npath_(opts.npath), - weighted_(opts.weighted), - remove_total_weight_(opts.remove_total_weight), - superfinal_(kNoLabel) { - SetType("randgen"); - SetProperties( - RandGenProperties(fst.Properties(kFstProperties, false), weighted_), - kCopyProperties); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - } - - RandGenFstImpl(const RandGenFstImpl &impl) - : CacheImpl(impl), - fst_(impl.fst_->Copy(true)), - sampler_(new Sampler(*impl.sampler_, fst_.get())), - npath_(impl.npath_), - weighted_(impl.weighted_), - superfinal_(kNoLabel) { - SetType("randgen"); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - StateId Start() { - if (!HasStart()) { - const auto s = fst_->Start(); - if (s == kNoStateId) return kNoStateId; - SetStart(state_table_.size()); - state_table_.emplace_back( - new RandState(s, npath_, 0, 0, nullptr)); - } - return CacheImpl::Start(); - } - - ToWeight Final(StateId s) { - if (!HasFinal(s)) Expand(s); - return CacheImpl::Final(s); - } - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && - (fst_->Properties(kError, false) || sampler_->Error())) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - // Computes the outgoing transitions from a state, creating new destination - // states as needed. - void Expand(StateId s) { - if (s == superfinal_) { - SetFinal(s); - SetArcs(s); - return; - } - SetFinal(s, ToWeight::Zero()); - const auto &rstate = *state_table_[s]; - sampler_->Sample(rstate); - ArcIterator> aiter(*fst_, rstate.state_id); - const auto narcs = fst_->NumArcs(rstate.state_id); - for (; !sampler_->Done(); sampler_->Next()) { - const auto &sample_pair = sampler_->Value(); - const auto pos = sample_pair.first; - const auto count = sample_pair.second; - double prob = static_cast(count) / rstate.nsamples; - if (pos < narcs) { // Regular transition. - aiter.Seek(sample_pair.first); - const auto &aarc = aiter.Value(); - auto weight = - weighted_ ? to_weight_(Log64Weight(-log(prob))) : ToWeight::One(); - EmplaceArc(s, aarc.ilabel, aarc.olabel, std::move(weight), - state_table_.size()); - auto nrstate = std::make_unique>( - aarc.nextstate, count, rstate.length + 1, pos, &rstate); - state_table_.push_back(std::move(nrstate)); - } else { // Super-final transition. - if (weighted_) { - const auto weight = - remove_total_weight_ - ? to_weight_(Log64Weight(-log(prob))) - : to_weight_(Log64Weight(-log(prob * npath_))); - SetFinal(s, weight); - } else { - if (superfinal_ == kNoLabel) { - superfinal_ = state_table_.size(); - state_table_.emplace_back( - new RandState(kNoStateId, 0, 0, 0, nullptr)); - } - for (size_t n = 0; n < count; ++n) EmplaceArc(s, 0, 0, superfinal_); - } - } - } - SetArcs(s); - } - - private: - const std::unique_ptr> fst_; - std::unique_ptr sampler_; - const int32_t npath_; - std::vector>> state_table_; - const bool weighted_; - bool remove_total_weight_; - StateId superfinal_; - const WeightConvert to_weight_{}; -}; - -} // namespace internal - -// FST class to randomly generate paths through an FST, with details controlled -// by RandGenOptionsFst. Output format is a tree weighted by the path count. -template -class RandGenFst - : public ImplToFst> { - public: - using Label = typename FromArc::Label; - using StateId = typename FromArc::StateId; - using Weight = typename FromArc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - - using Impl = internal::RandGenFstImpl; - - friend class ArcIterator>; - friend class StateIterator>; - - RandGenFst(const Fst &fst, const RandGenFstOptions &opts) - : ImplToFst(std::make_shared(fst, opts)) {} - - // See Fst<>::Copy() for doc. - RandGenFst(const RandGenFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Get a copy of this RandGenFst. See Fst<>::Copy() for further doc. - RandGenFst *Copy(bool safe = false) const override { - return new RandGenFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - RandGenFst &operator=(const RandGenFst &) = delete; -}; - -// Specialization for RandGenFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const RandGenFst &fst) - : CacheStateIterator>( - fst, fst.GetMutableImpl()) {} -}; - -// Specialization for RandGenFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename FromArc::StateId; - - ArcIterator(const RandGenFst &fst, StateId s) - : CacheArcIterator>( - fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void RandGenFst::InitStateIterator( - StateIteratorData *data) const { - data->base = - std::make_unique>>( - *this); -} - -// Options for random path generation. -template -struct RandGenOptions { - const Selector &selector; // How an arc is selected at a state. - int32_t max_length; // Maximum path length. - int32_t npath; // Number of paths to generate. - bool weighted; // Is the output tree weighted by path count, or - // is it just an unweighted DAG? - bool remove_total_weight; // Remove total weight when output is weighted? - - explicit RandGenOptions( - const Selector &selector, - int32_t max_length = std::numeric_limits::max(), - int32_t npath = 1, bool weighted = false, - bool remove_total_weight = false) - : selector(selector), - max_length(max_length), - npath(npath), - weighted(weighted), - remove_total_weight(remove_total_weight) {} -}; - -namespace internal { - -template -class RandGenVisitor { - public: - using StateId = typename FromArc::StateId; - using Weight = typename FromArc::Weight; - - explicit RandGenVisitor(MutableFst *ofst) : ofst_(ofst) {} - - void InitVisit(const Fst &ifst) { - ifst_ = &ifst; - ofst_->DeleteStates(); - ofst_->SetInputSymbols(ifst.InputSymbols()); - ofst_->SetOutputSymbols(ifst.OutputSymbols()); - if (ifst.Properties(kError, false)) ofst_->SetProperties(kError, kError); - path_.clear(); - } - - constexpr bool InitState(StateId, StateId) const { return true; } - - bool TreeArc(StateId, const ToArc &arc) { - if (ifst_->Final(arc.nextstate) == Weight::Zero()) { - path_.push_back(arc); - } else { - OutputPath(); - } - return true; - } - - bool BackArc(StateId, const FromArc &) { - FSTERROR() << "RandGenVisitor: cyclic input"; - ofst_->SetProperties(kError, kError); - return false; - } - - bool ForwardOrCrossArc(StateId, const FromArc &) { - OutputPath(); - return true; - } - - void FinishState(StateId s, StateId p, const FromArc *) { - if (p != kNoStateId && ifst_->Final(s) == Weight::Zero()) path_.pop_back(); - } - - void FinishVisit() {} - - private: - void OutputPath() { - if (ofst_->Start() == kNoStateId) { - const auto start = ofst_->AddState(); - ofst_->SetStart(start); - } - auto src = ofst_->Start(); - for (size_t i = 0; i < path_.size(); ++i) { - const auto dest = ofst_->AddState(); - const ToArc arc(path_[i].ilabel, path_[i].olabel, Weight::One(), dest); - ofst_->AddArc(src, arc); - src = dest; - } - ofst_->SetFinal(src); - } - - const Fst *ifst_; - MutableFst *ofst_; - std::vector path_; - - RandGenVisitor(const RandGenVisitor &) = delete; - RandGenVisitor &operator=(const RandGenVisitor &) = delete; -}; - -} // namespace internal - -// Randomly generate paths through an FST; details controlled by -// RandGenOptions. -template -void RandGen(const Fst &ifst, MutableFst *ofst, - const RandGenOptions &opts) { - using Sampler = ArcSampler; - auto sampler = - std::make_unique(ifst, opts.selector, opts.max_length); - RandGenFstOptions fopts(CacheOptions(true, 0), sampler.release(), - opts.npath, opts.weighted, - opts.remove_total_weight); - RandGenFst rfst(ifst, fopts); - if (opts.weighted) { - *ofst = rfst; - } else { - internal::RandGenVisitor rand_visitor(ofst); - DfsVisit(rfst, &rand_visitor); - } -} - -// Randomly generate a path through an FST with the uniform distribution -// over the transitions. -template -void RandGen(const Fst &ifst, MutableFst *ofst, - uint64_t seed = std::random_device()()) { - const UniformArcSelector uniform_selector(seed); - RandGenOptions> opts(uniform_selector); - RandGen(ifst, ofst, opts); -} - -} // namespace fst - -#endif // FST_RANDGEN_H_ diff --git a/contrib/fstlib/fst/rational.h b/contrib/fstlib/fst/rational.h deleted file mode 100644 index 4b2201d..0000000 --- a/contrib/fstlib/fst/rational.h +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// An FST implementation and base interface for delayed unions, concatenations, -// and closures. - -#ifndef FST_RATIONAL_H_ -#define FST_RATIONAL_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -using RationalFstOptions = CacheOptions; - -// This specifies whether to add the empty string. -enum ClosureType { - CLOSURE_STAR = 0, // Add the empty string. - CLOSURE_PLUS = 1 // Don't add the empty string. -}; - -template -class RationalFst; - -template -void Union(RationalFst *fst1, const Fst &fst2); - -template -void Concat(RationalFst *fst1, const Fst &fst2); - -template -void Concat(const Fst &fst1, RationalFst *fst2); - -template -void Closure(RationalFst *fst, ClosureType closure_type); - -namespace internal { - -// Implementation class for delayed unions, concatenations and closures. -template -class RationalFstImpl : public FstImpl { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::WriteHeader; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - explicit RationalFstImpl(const RationalFstOptions &opts) - : nonterminals_(0), replace_options_(opts, 0) { - SetType("rational"); - fst_tuples_.emplace_back(0, nullptr); - } - - RationalFstImpl(const RationalFstImpl &impl) - : rfst_(impl.rfst_), - nonterminals_(impl.nonterminals_), - replace_(impl.replace_ ? impl.replace_->Copy(true) : nullptr), - replace_options_(impl.replace_options_) { - SetType("rational"); - fst_tuples_.reserve(impl.fst_tuples_.size()); - for (const auto &pair : impl.fst_tuples_) { - fst_tuples_.emplace_back(pair.first, - pair.second ? pair.second->Copy(true) : nullptr); - } - } - - ~RationalFstImpl() override { - for (auto &tuple : fst_tuples_) delete tuple.second; - } - - StateId Start() { return Replace()->Start(); } - - Weight Final(StateId s) { return Replace()->Final(s); } - - size_t NumArcs(StateId s) { return Replace()->NumArcs(s); } - - size_t NumInputEpsilons(StateId s) { return Replace()->NumInputEpsilons(s); } - - size_t NumOutputEpsilons(StateId s) { - return Replace()->NumOutputEpsilons(s); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && Replace()->Properties(kError, false)) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - // Implementation of UnionFst(fst1, fst2). - void InitUnion(const Fst &fst1, const Fst &fst2) { - replace_.reset(); - const auto props1 = fst1.Properties(kFstProperties, false); - const auto props2 = fst2.Properties(kFstProperties, false); - SetInputSymbols(fst1.InputSymbols()); - SetOutputSymbols(fst1.OutputSymbols()); - rfst_.AddState(); - rfst_.AddState(); - rfst_.SetStart(0); - rfst_.SetFinal(1); - rfst_.SetInputSymbols(fst1.InputSymbols()); - rfst_.SetOutputSymbols(fst1.OutputSymbols()); - nonterminals_ = 2; - rfst_.EmplaceArc(0, 0, -1, Weight::One(), 1); - rfst_.EmplaceArc(0, 0, -2, Weight::One(), 1); - fst_tuples_.emplace_back(-1, fst1.Copy()); - fst_tuples_.emplace_back(-2, fst2.Copy()); - SetProperties(UnionProperties(props1, props2, true), kCopyProperties); - } - - // Implementation of ConcatFst(fst1, fst2). - void InitConcat(const Fst &fst1, const Fst &fst2) { - replace_.reset(); - const auto props1 = fst1.Properties(kFstProperties, false); - const auto props2 = fst2.Properties(kFstProperties, false); - SetInputSymbols(fst1.InputSymbols()); - SetOutputSymbols(fst1.OutputSymbols()); - rfst_.AddState(); - rfst_.AddState(); - rfst_.AddState(); - rfst_.SetStart(0); - rfst_.SetFinal(2); - rfst_.SetInputSymbols(fst1.InputSymbols()); - rfst_.SetOutputSymbols(fst1.OutputSymbols()); - nonterminals_ = 2; - rfst_.EmplaceArc(0, 0, -1, Weight::One(), 1); - rfst_.EmplaceArc(1, 0, -2, Weight::One(), 2); - fst_tuples_.emplace_back(-1, fst1.Copy()); - fst_tuples_.emplace_back(-2, fst2.Copy()); - SetProperties(ConcatProperties(props1, props2, true), kCopyProperties); - } - - // Implementation of ClosureFst(fst, closure_type). - void InitClosure(const Fst &fst, ClosureType closure_type) { - replace_.reset(); - const auto props = fst.Properties(kFstProperties, false); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - if (closure_type == CLOSURE_STAR) { - rfst_.AddState(); - rfst_.SetStart(0); - rfst_.SetFinal(0); - rfst_.EmplaceArc(0, 0, -1, Weight::One(), 0); - } else { - rfst_.AddState(); - rfst_.AddState(); - rfst_.SetStart(0); - rfst_.SetFinal(1); - rfst_.EmplaceArc(0, 0, -1, Weight::One(), 1); - rfst_.EmplaceArc(1, 0, 0, Weight::One(), 0); - } - rfst_.SetInputSymbols(fst.InputSymbols()); - rfst_.SetOutputSymbols(fst.OutputSymbols()); - fst_tuples_.emplace_back(-1, fst.Copy()); - nonterminals_ = 1; - SetProperties(ClosureProperties(props, closure_type == CLOSURE_STAR, true), - kCopyProperties); - } - - // Implementation of Union(Fst &, RationalFst *). - void AddUnion(const Fst &fst) { - replace_.reset(); - const auto props1 = FstImpl::Properties(); - const auto props2 = fst.Properties(kFstProperties, false); - VectorFst afst; - afst.AddState(); - afst.AddState(); - afst.SetStart(0); - afst.SetFinal(1); - ++nonterminals_; - afst.EmplaceArc(0, 0, -nonterminals_, Weight::One(), 1); - Union(&rfst_, afst); - fst_tuples_.emplace_back(-nonterminals_, fst.Copy()); - SetProperties(UnionProperties(props1, props2, true), kCopyProperties); - } - - // Implementation of Concat(Fst &, RationalFst *). - void AddConcat(const Fst &fst, bool append) { - replace_.reset(); - const auto props1 = FstImpl::Properties(); - const auto props2 = fst.Properties(kFstProperties, false); - VectorFst afst; - afst.AddState(); - afst.AddState(); - afst.SetStart(0); - afst.SetFinal(1); - ++nonterminals_; - afst.EmplaceArc(0, 0, -nonterminals_, Weight::One(), 1); - if (append) { - Concat(&rfst_, afst); - } else { - Concat(afst, &rfst_); - } - fst_tuples_.emplace_back(-nonterminals_, fst.Copy()); - SetProperties(ConcatProperties(props1, props2, true), kCopyProperties); - } - - // Implementation of Closure(RationalFst *, closure_type). - void AddClosure(ClosureType closure_type) { - replace_.reset(); - const auto props = FstImpl::Properties(); - Closure(&rfst_, closure_type); - SetProperties(ClosureProperties(props, closure_type == CLOSURE_STAR, true), - kCopyProperties); - } - - // Returns the underlying ReplaceFst, preserving ownership of the underlying - // object. - ReplaceFst *Replace() const { - if (!replace_) { - fst_tuples_[0].second = rfst_.Copy(); - replace_ = - std::make_unique>(fst_tuples_, replace_options_); - } - return replace_.get(); - } - - private: - // Rational topology machine, using negative non-terminals. - VectorFst rfst_; - // Number of nonterminals used. - Label nonterminals_; - // Contains the nonterminals and their corresponding FSTs. - mutable std::vector *>> fst_tuples_; - // Underlying ReplaceFst. - mutable std::unique_ptr> replace_; - const ReplaceFstOptions replace_options_; -}; - -} // namespace internal - -// Parent class for the delayed rational operations (union, concatenation, and -// closure). This class attaches interface to implementation and handles -// reference counting, delegating most methods to ImplToFst. -template -class RationalFst : public ImplToFst> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using Impl = internal::RationalFstImpl; - - friend class StateIterator>; - friend class ArcIterator>; - friend void Union<>(RationalFst *fst1, const Fst &fst2); - friend void Concat<>(RationalFst *fst1, const Fst &fst2); - friend void Concat<>(const Fst &fst1, RationalFst *fst2); - friend void Closure<>(RationalFst *fst, ClosureType closure_type); - - void InitStateIterator(StateIteratorData *data) const override { - GetImpl()->Replace()->InitStateIterator(data); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetImpl()->Replace()->InitArcIterator(s, data); - } - - protected: - using ImplToFst::GetImpl; - - explicit RationalFst(const RationalFstOptions &opts = RationalFstOptions()) - : ImplToFst(std::make_shared(opts)) {} - - // See Fst<>::Copy() for doc. - RationalFst(const RationalFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - private: - RationalFst &operator=(const RationalFst &) = delete; -}; - -// Specialization for RationalFst. -template -class StateIterator> : public StateIterator> { - public: - explicit StateIterator(const RationalFst &fst) - : StateIterator>(*(fst.GetImpl()->Replace())) {} -}; - -// Specialization for RationalFst. -template -class ArcIterator> : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const RationalFst &fst, StateId s) - : ArcIterator>(*(fst.GetImpl()->Replace()), s) {} -}; - -} // namespace fst - -#endif // FST_RATIONAL_H_ diff --git a/contrib/fstlib/fst/register.h b/contrib/fstlib/fst/register.h deleted file mode 100644 index ecd24ae..0000000 --- a/contrib/fstlib/fst/register.h +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes for registering derived FST for generic reading. - -#ifndef FST_REGISTER_H_ -#define FST_REGISTER_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -template -class FstRegisterer; -struct FstReadOptions; -template -class Fst; -template -class FstRegisterer; - -// This class represents a single entry in a FstRegister -template -struct FstRegisterEntry { - using Reader = Fst *(*)(std::istream &istrm, const FstReadOptions &opts); - using Converter = Fst *(*)(const Fst &fst); - - Reader reader; - Converter converter; - - explicit FstRegisterEntry(Reader reader = nullptr, - Converter converter = nullptr) - : reader(reader), converter(converter) {} -}; - -// This class maintains the correspondence between a string describing -// an FST type, and its reader and converter. -template -class FstRegister : public GenericRegister, - FstRegister> { - public: - using Reader = typename FstRegisterEntry::Reader; - using Converter = typename FstRegisterEntry::Converter; - - const Reader GetReader(std::string_view type) const { - return this->GetEntry(type).reader; - } - - const Converter GetConverter(std::string_view type) const { - return this->GetEntry(type).converter; - } - - protected: - std::string ConvertKeyToSoFilename(std::string_view key) const override { - std::string legal_type(key); - ConvertToLegalCSymbol(&legal_type); - legal_type.append("-fst.so"); - return legal_type; - } -}; - -// This class registers an FST type for generic reading and creating. -// The type must have a default constructor and a copy constructor from -// Fst. -template -class FstRegisterer : public GenericRegisterer> { - public: - using Arc = typename FST::Arc; - using Entry = typename FstRegister::Entry; - using Reader = typename FstRegister::Reader; - - FstRegisterer() - : GenericRegisterer>(FST().Type(), - BuildEntry()) {} - - private: - static Fst *ReadGeneric(std::istream &strm, const FstReadOptions &opts) { - static_assert(std::is_base_of_v, FST>, - "FST class does not inherit from Fst"); - return FST::Read(strm, opts); - } - - static Entry BuildEntry() { - return Entry(&ReadGeneric, &FstRegisterer::Convert); - } - - static Fst *Convert(const Fst &fst) { return new FST(fst); } -}; - -// Convenience macro to generate a static FstRegisterer instance. -// `FST` and `Arc` must be identifiers (that is, not a qualified type). -// Users SHOULD NOT register within the fst namespace. To register an -// FST for StdArc, for example, use: -// namespace example { -// using fst::StdArc; -// REGISTER_FST(MyFst, StdArc); -// } // namespace example -#define REGISTER_FST(FST, Arc) \ - static fst::FstRegisterer> FST##_##Arc##_registerer - -// Converts an FST to the specified type. -template -Fst *Convert(const Fst &fst, std::string_view fst_type) { - auto *reg = FstRegister::GetRegister(); - const auto converter = reg->GetConverter(fst_type); - if (!converter) { - FSTERROR() << "Fst::Convert: Unknown FST type " << fst_type << " (arc type " - << Arc::Type() << ")"; - return nullptr; - } - return converter(fst); -} - -} // namespace fst - -#endif // FST_REGISTER_H_ diff --git a/contrib/fstlib/fst/relabel.h b/contrib/fstlib/fst/relabel.h deleted file mode 100644 index 28a7177..0000000 --- a/contrib/fstlib/fst/relabel.h +++ /dev/null @@ -1,484 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to relabel an FST (either on input or output). - -#ifndef FST_RELABEL_H_ -#define FST_RELABEL_H_ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Relabels either the input labels or output labels. The old to -// new labels are specified using a vector of std::pair. -// Any label associations not specified are assumed to be identity -// mapping. The destination labels must be valid labels (e.g., not kNoLabel). -template -void Relabel( - MutableFst *fst, - const std::vector> - &ipairs, - const std::vector> - &opairs) { - using Label = typename Arc::Label; - const auto props = fst->Properties(kFstProperties, false); - // Constructs label-to-label maps. - const std::unordered_map input_map( - ipairs.begin(), ipairs.end()); - const std::unordered_map output_map( - opairs.begin(), opairs.end()); - for (StateIterator> siter(*fst); !siter.Done(); - siter.Next()) { - for (MutableArcIterator> aiter(fst, siter.Value()); - !aiter.Done(); aiter.Next()) { - auto arc = aiter.Value(); - // dense_hash_map does not support find on the empty_key_val. - // These labels should never be in an FST anyway. - DCHECK_NE(arc.ilabel, kNoLabel); - DCHECK_NE(arc.olabel, kNoLabel); - // Relabels input. - if (auto it = input_map.find(arc.ilabel); it != input_map.end()) { - if (it->second == kNoLabel) { - FSTERROR() << "Input symbol ID " << arc.ilabel - << " missing from target vocabulary"; - fst->SetProperties(kError, kError); - return; - } - arc.ilabel = it->second; - } - // Relabels output. - if (auto it = output_map.find(arc.olabel); it != output_map.end()) { - if (it->second == kNoLabel) { - FSTERROR() << "Output symbol id " << arc.olabel - << " missing from target vocabulary"; - fst->SetProperties(kError, kError); - return; - } - arc.olabel = it->second; - } - aiter.SetValue(arc); - } - } - fst->SetProperties(RelabelProperties(props), kFstProperties); -} - -// Relabels either the input labels or output labels. The old to -// new labels are specified using pairs of old and new symbol tables. -// The tables must contain (at least) all labels on the appropriate side of the -// FST. If the 'unknown_i(o)symbol' is non-empty, it is used to label any -// missing symbol in new_i(o)symbols table. -template -void Relabel(MutableFst *fst, const SymbolTable *old_isymbols, - const SymbolTable *new_isymbols, - const std::string &unknown_isymbol, bool attach_new_isymbols, - const SymbolTable *old_osymbols, const SymbolTable *new_osymbols, - const std::string &unknown_osymbol, bool attach_new_osymbols) { - using Label = typename Arc::Label; - // Constructs vectors of input-side label pairs. - std::vector> ipairs; - if (old_isymbols && new_isymbols) { - size_t num_missing_syms = 0; - Label unknown_ilabel = kNoLabel; - if (!unknown_isymbol.empty()) { - unknown_ilabel = new_isymbols->Find(unknown_isymbol); - if (unknown_ilabel == kNoLabel) { - VLOG(1) << "Input symbol '" << unknown_isymbol - << "' missing from target symbol table"; - ++num_missing_syms; - } - } - - for (const auto &sitem : *old_isymbols) { - const auto old_index = sitem.Label(); - const auto symbol = sitem.Symbol(); - auto new_index = new_isymbols->Find(symbol); - if (new_index == kNoLabel) { - if (unknown_ilabel != kNoLabel) { - new_index = unknown_ilabel; - } else { - VLOG(1) << "Input symbol ID " << old_index << " symbol '" << symbol - << "' missing from target symbol table"; - ++num_missing_syms; - } - } - ipairs.emplace_back(old_index, new_index); - } - if (num_missing_syms > 0) { - LOG(WARNING) << "Target symbol table missing: " << num_missing_syms - << " input symbols"; - } - if (attach_new_isymbols) fst->SetInputSymbols(new_isymbols); - } - // Constructs vectors of output-side label pairs. - std::vector> opairs; - if (old_osymbols && new_osymbols) { - size_t num_missing_syms = 0; - Label unknown_olabel = kNoLabel; - if (!unknown_osymbol.empty()) { - unknown_olabel = new_osymbols->Find(unknown_osymbol); - if (unknown_olabel == kNoLabel) { - VLOG(1) << "Output symbol '" << unknown_osymbol - << "' missing from target symbol table"; - ++num_missing_syms; - } - } - for (const auto &sitem : *old_osymbols) { - const auto old_index = sitem.Label(); - const auto symbol = sitem.Symbol(); - auto new_index = new_osymbols->Find(symbol); - if (new_index == kNoLabel) { - if (unknown_olabel != kNoLabel) { - new_index = unknown_olabel; - } else { - VLOG(1) << "Output symbol ID " << old_index << " symbol '" << symbol - << "' missing from target symbol table"; - ++num_missing_syms; - } - } - opairs.emplace_back(old_index, new_index); - } - if (num_missing_syms > 0) { - LOG(WARNING) << "Target symbol table missing: " << num_missing_syms - << " output symbols"; - } - if (attach_new_osymbols) fst->SetOutputSymbols(new_osymbols); - } - // Calls relabel using vector of relabel pairs. - Relabel(fst, ipairs, opairs); -} - -// Same as previous but no special allowance for unknown symbols. Kept -// for backward compat. -template -void Relabel(MutableFst *fst, const SymbolTable *old_isymbols, - const SymbolTable *new_isymbols, bool attach_new_isymbols, - const SymbolTable *old_osymbols, const SymbolTable *new_osymbols, - bool attach_new_osymbols) { - Relabel(fst, old_isymbols, new_isymbols, "" /* no unknown isymbol */, - attach_new_isymbols, old_osymbols, new_osymbols, - "" /* no unknown osymbol */, attach_new_osymbols); -} - -// Relabels either the input labels or output labels. The old to -// new labels are specified using symbol tables. Any label associations not -// specified are assumed to be identity mapping. -template -void Relabel(MutableFst *fst, const SymbolTable *new_isymbols, - const SymbolTable *new_osymbols) { - Relabel(fst, fst->InputSymbols(), new_isymbols, true, fst->OutputSymbols(), - new_osymbols, true); -} - -using RelabelFstOptions = CacheOptions; - -template -class RelabelFst; - -namespace internal { - -// Relabels an FST from one symbol set to another. Relabeling can either be on -// input or output space. RelabelFst implements a delayed version of the -// relabel. Arcs are relabeled on the fly and not cached; i.e., each request is -// recomputed. -template -class RelabelFstImpl : public CacheImpl { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::WriteHeader; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheImpl::PushArc; - using CacheImpl::HasArcs; - using CacheImpl::HasFinal; - using CacheImpl::HasStart; - using CacheImpl::SetArcs; - using CacheImpl::SetFinal; - using CacheImpl::SetStart; - - friend class StateIterator>; - - RelabelFstImpl(const Fst &fst, - const std::vector> &ipairs, - const std::vector> &opairs, - const RelabelFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - input_map_(ipairs.begin(), ipairs.end()), - output_map_(opairs.begin(), opairs.end()), - relabel_input_(!ipairs.empty()), - relabel_output_(!opairs.empty()) { - SetProperties(RelabelProperties(fst.Properties(kCopyProperties, false))); - SetType("relabel"); - } - - RelabelFstImpl(const Fst &fst, const SymbolTable *old_isymbols, - const SymbolTable *new_isymbols, - const SymbolTable *old_osymbols, - const SymbolTable *new_osymbols, const RelabelFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - relabel_input_(false), - relabel_output_(false) { - SetType("relabel"); - SetProperties(RelabelProperties(fst.Properties(kCopyProperties, false))); - SetInputSymbols(old_isymbols); - SetOutputSymbols(old_osymbols); - if (old_isymbols && new_isymbols && - old_isymbols->LabeledCheckSum() != new_isymbols->LabeledCheckSum()) { - for (const auto &sitem : *old_isymbols) { - input_map_[sitem.Label()] = new_isymbols->Find(sitem.Symbol()); - } - SetInputSymbols(new_isymbols); - relabel_input_ = true; - } - if (old_osymbols && new_osymbols && - old_osymbols->LabeledCheckSum() != new_osymbols->LabeledCheckSum()) { - for (const auto &sitem : *old_osymbols) { - output_map_[sitem.Label()] = new_osymbols->Find(sitem.Symbol()); - } - SetOutputSymbols(new_osymbols); - relabel_output_ = true; - } - } - - RelabelFstImpl(const RelabelFstImpl &impl) - : CacheImpl(impl), - fst_(impl.fst_->Copy(true)), - input_map_(impl.input_map_), - output_map_(impl.output_map_), - relabel_input_(impl.relabel_input_), - relabel_output_(impl.relabel_output_) { - SetType("relabel"); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - StateId Start() { - if (!HasStart()) SetStart(fst_->Start()); - return CacheImpl::Start(); - } - - Weight Final(StateId s) { - if (!HasFinal(s)) SetFinal(s, fst_->Final(s)); - return CacheImpl::Final(s); - } - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found, and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && fst_->Properties(kError, false)) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - void Expand(StateId s) { - for (ArcIterator> aiter(*fst_, s); !aiter.Done(); aiter.Next()) { - auto arc = aiter.Value(); - if (relabel_input_) { - if (auto it = input_map_.find(arc.ilabel); it != input_map_.end()) { - arc.ilabel = it->second; - } - } - if (relabel_output_) { - if (auto it = output_map_.find(arc.olabel); it != output_map_.end()) { - arc.olabel = it->second; - } - } - PushArc(s, std::move(arc)); - } - SetArcs(s); - } - - private: - std::unique_ptr> fst_; - - std::unordered_map input_map_; - std::unordered_map output_map_; - bool relabel_input_; - bool relabel_output_; -}; - -} // namespace internal - -// This class attaches interface to implementation and handles -// reference counting, delegating most methods to ImplToFst. -template -class RelabelFst : public ImplToFst> { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - using Impl = internal::RelabelFstImpl; - - friend class ArcIterator>; - friend class StateIterator>; - - RelabelFst(const Fst &fst, - const std::vector> &ipairs, - const std::vector> &opairs, - const RelabelFstOptions &opts = RelabelFstOptions()) - : ImplToFst(std::make_shared(fst, ipairs, opairs, opts)) {} - - RelabelFst(const Fst &fst, const SymbolTable *new_isymbols, - const SymbolTable *new_osymbols, - const RelabelFstOptions &opts = RelabelFstOptions()) - : ImplToFst( - std::make_shared(fst, fst.InputSymbols(), new_isymbols, - fst.OutputSymbols(), new_osymbols, opts)) {} - - RelabelFst(const Fst &fst, const SymbolTable *old_isymbols, - const SymbolTable *new_isymbols, const SymbolTable *old_osymbols, - const SymbolTable *new_osymbols, - const RelabelFstOptions &opts = RelabelFstOptions()) - : ImplToFst(std::make_shared(fst, old_isymbols, new_isymbols, - old_osymbols, new_osymbols, - opts)) {} - - // See Fst<>::Copy() for doc. - RelabelFst(const RelabelFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Gets a copy of this RelabelFst. See Fst<>::Copy() for further doc. - RelabelFst *Copy(bool safe = false) const override { - return new RelabelFst(*this, safe); - } - - void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - return GetMutableImpl()->InitArcIterator(s, data); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - RelabelFst &operator=(const RelabelFst &) = delete; -}; - -// Specialization for RelabelFst. -template -class StateIterator> : public StateIteratorBase { - public: - using StateId = typename Arc::StateId; - - explicit StateIterator(const RelabelFst &fst) - : impl_(fst.GetImpl()), siter_(*impl_->fst_), s_(0) {} - - bool Done() const final { return siter_.Done(); } - - StateId Value() const final { return s_; } - - void Next() final { - if (!siter_.Done()) { - ++s_; - siter_.Next(); - } - } - - void Reset() final { - s_ = 0; - siter_.Reset(); - } - - private: - const internal::RelabelFstImpl *impl_; - StateIterator> siter_; - StateId s_; - - StateIterator(const StateIterator &) = delete; - StateIterator &operator=(const StateIterator &) = delete; -}; - -// Specialization for RelabelFst. -template -class ArcIterator> : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const RelabelFst &fst, StateId s) - : CacheArcIterator>(fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void RelabelFst::InitStateIterator( - StateIteratorData *data) const { - data->base = std::make_unique>>(*this); -} - -// Useful alias when using StdArc. -using StdRelabelFst = RelabelFst; - -} // namespace fst - -#endif // FST_RELABEL_H_ diff --git a/contrib/fstlib/fst/replace-util.h b/contrib/fstlib/fst/replace-util.h deleted file mode 100644 index 3a0c754..0000000 --- a/contrib/fstlib/fst/replace-util.h +++ /dev/null @@ -1,650 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Utility classes for the recursive replacement of FSTs (RTNs). - -#ifndef FST_REPLACE_UTIL_H_ -#define FST_REPLACE_UTIL_H_ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// This specifies what labels to output on the call or return arc. Note that -// REPLACE_LABEL_INPUT and REPLACE_LABEL_OUTPUT will produce transducers when -// applied to acceptors. -enum ReplaceLabelType { - // Epsilon labels on both input and output. - REPLACE_LABEL_NEITHER = 1, - // Non-epsilon labels on input and epsilon on output. - REPLACE_LABEL_INPUT = 2, - // Epsilon on input and non-epsilon on output. - REPLACE_LABEL_OUTPUT = 3, - // Non-epsilon labels on both input and output. - REPLACE_LABEL_BOTH = 4 -}; - -// By default ReplaceUtil will copy the input label of the replace arc. -// The call_label_type and return_label_type options specify how to manage -// the labels of the call arc and the return arc of the replace FST -struct ReplaceUtilOptions { - int64_t root; // Root rule for expansion. - ReplaceLabelType call_label_type; // How to label call arc. - ReplaceLabelType return_label_type; // How to label return arc. - int64_t return_label; // Label to put on return arc. - - explicit ReplaceUtilOptions( - int64_t root = kNoLabel, - ReplaceLabelType call_label_type = REPLACE_LABEL_INPUT, - ReplaceLabelType return_label_type = REPLACE_LABEL_NEITHER, - int64_t return_label = 0) - : root(root), - call_label_type(call_label_type), - return_label_type(return_label_type), - return_label(return_label) {} - - // For backwards compatibility. - ReplaceUtilOptions(int64_t root, bool epsilon_replace_arc) - : ReplaceUtilOptions(root, epsilon_replace_arc ? REPLACE_LABEL_NEITHER - : REPLACE_LABEL_INPUT) {} -}; - -// Every non-terminal on a path appears as the first label on that path in every -// FST associated with a given SCC of the replace dependency graph. This would -// be true if the SCC were formed from left-linear grammar rules. -inline constexpr uint8_t kReplaceSCCLeftLinear = 0x01; -// Every non-terminal on a path appears as the final label on that path in every -// FST associated with a given SCC of the replace dependency graph. This would -// be true if the SCC were formed from right-linear grammar rules. -inline constexpr uint8_t kReplaceSCCRightLinear = 0x02; -// The SCC in the replace dependency graph has more than one state or a -// self-loop. -inline constexpr uint8_t kReplaceSCCNonTrivial = 0x04; - -// Defined in replace.h. -template -void Replace( - const std::vector *>> &, - MutableFst *, const ReplaceUtilOptions &); - -// Utility class for the recursive replacement of FSTs (RTNs). The user provides -// a set of label/FST pairs at construction. These are used by methods for -// testing cyclic dependencies and connectedness and doing RTN connection and -// specific FST replacement by label or for various optimization properties. The -// modified results can be obtained with the GetFstPairs() or -// GetMutableFstPairs() methods. -template -class ReplaceUtil { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstPair = std::pair *>; - using MutableFstPair = std::pair *>; - using NonTerminalHash = std::unordered_map; - - // Constructs from mutable FSTs; FST ownership is given to ReplaceUtil. - ReplaceUtil(const std::vector &fst_pairs, - const ReplaceUtilOptions &opts); - - // Constructs from FSTs; FST ownership is retained by caller. - ReplaceUtil(const std::vector &fst_pairs, - const ReplaceUtilOptions &opts); - - // Constructs from ReplaceFst internals; FST ownership is retained by caller. - ReplaceUtil(const std::vector>> &fst_array, - const NonTerminalHash &nonterminal_hash, - const ReplaceUtilOptions &opts); - - ~ReplaceUtil() { - for (Label i = 0; i < fst_array_.size(); ++i) delete fst_array_[i]; - } - - // True if the non-terminal dependencies are cyclic. Cyclic dependencies will - // result in an unexpandable FST. - bool CyclicDependencies() const { - GetDependencies(false); - return depprops_ & kCyclic; - } - - // Returns the strongly-connected component ID in the dependency graph of the - // replace FSTS. - StateId SCC(Label label) const { - GetDependencies(false); - if (const auto it = nonterminal_hash_.find(label); - it != nonterminal_hash_.end()) { - return depscc_[it->second]; - } - return kNoStateId; - } - - // Returns properties for the strongly-connected component in the dependency - // graph of the replace FSTs. If the SCC is kReplaceSCCLeftLinear or - // kReplaceSCCRightLinear, that SCC can be represented as finite-state despite - // any cyclic dependencies, but not by the usual replacement operation (see - // fst/extensions/pdt/replace.h). - uint8_t SCCProperties(StateId scc_id) { - GetSCCProperties(); - return depsccprops_[scc_id]; - } - - // Returns true if no useless FSTs, states or transitions are present in the - // RTN. - bool Connected() const { - GetDependencies(false); - uint64_t props = kAccessible | kCoAccessible; - for (Label i = 0; i < fst_array_.size(); ++i) { - if (!fst_array_[i]) continue; - if (fst_array_[i]->Properties(props, true) != props || !depaccess_[i]) { - return false; - } - } - return true; - } - - // Removes useless FSTs, states and transitions from the RTN. - void Connect(); - - // Replaces FSTs specified by labels, unless there are cyclic dependencies. - void ReplaceLabels(const std::vector */> -class ReplaceFst - : public ImplToFst> { - public: - using Arc = A; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using StateTable = T; - using Store = CacheStore; - using State = typename CacheStore::State; - using Impl = internal::ReplaceFstImpl; - using CacheImpl = internal::CacheBaseImpl; - - using ImplToFst::Properties; - - friend class ArcIterator>; - friend class StateIterator>; - friend class ReplaceFstMatcher; - - ReplaceFst(const std::vector *>> &fst_array, - Label root) - : ImplToFst(std::make_shared( - fst_array, ReplaceFstOptions(root))) {} - - ReplaceFst(const std::vector *>> &fst_array, - const ReplaceFstOptions &opts) - : ImplToFst(std::make_shared(fst_array, opts)) {} - - // See Fst<>::Copy() for doc. - ReplaceFst(const ReplaceFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Get a copy of this ReplaceFst. See Fst<>::Copy() for further doc. - ReplaceFst *Copy(bool safe = false) const override { - return new ReplaceFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - MatcherBase *InitMatcher(MatchType match_type) const override { - if ((GetImpl()->ArcIteratorFlags() & kArcNoCache) && - ((match_type == MATCH_INPUT && Properties(kILabelSorted, false)) || - (match_type == MATCH_OUTPUT && Properties(kOLabelSorted, false)))) { - return new ReplaceFstMatcher(this, - match_type); - } else { - VLOG(2) << "Not using replace matcher"; - return nullptr; - } - } - - bool CyclicDependencies() const { return GetImpl()->CyclicDependencies(); } - - const StateTable &GetStateTable() const { - return *GetImpl()->GetStateTable(); - } - - const Fst &GetFst(Label nonterminal) const { - return *GetImpl()->GetFst(GetImpl()->GetFstId(nonterminal)); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - ReplaceFst &operator=(const ReplaceFst &) = delete; -}; - -// Specialization for ReplaceFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const ReplaceFst &fst) - : CacheStateIterator>( - fst, fst.GetMutableImpl()) {} -}; - -// Specialization for ReplaceFst, implementing optional caching. It is be used -// as follows: -// -// ReplaceFst replace; -// ArcIterator> aiter(replace, s); -// // Note: ArcIterator< Fst> is always a caching arc iterator. -// aiter.SetFlags(kArcNoCache, kArcNoCache); -// // Uses the arc iterator, no arc will be cached, no state will be expanded. -// // Arc flags can be used to decide which component of the arc need to be -// computed. -// aiter.SetFlags(kArcILabelValue, kArcValueFlags); -// // Wants the ilabel for this arc. -// aiter.Value(); // Does not compute the destination state. -// aiter.Next(); -// aiter.SetFlags(kArcNextStateValue, kArcNextStateValue); -// // Wants the ilabel and next state for this arc. -// aiter.Value(); // Does compute the destination state and inserts it -// // in the replace state table. -// // No additional arcs have been cached at this point. -template -class ArcIterator> { - public: - using StateId = typename Arc::StateId; - - using StateTuple = typename StateTable::StateTuple; - - ArcIterator(const ReplaceFst &fst, StateId s) - : fst_(fst), - s_(s), - pos_(0), - offset_(0), - flags_(kArcValueFlags), - arcs_(nullptr), - data_flags_(0), - final_flags_(0) { - cache_data_.ref_count = nullptr; - local_data_.ref_count = nullptr; - // If FST does not support optional caching, forces caching. - if (!(fst_.GetImpl()->ArcIteratorFlags() & kArcNoCache) && - !(fst_.GetImpl()->HasArcs(s_))) { - fst_.GetMutableImpl()->Expand(s_); - } - // If state is already cached, use cached arcs array. - if (fst_.GetImpl()->HasArcs(s_)) { - (fst_.GetImpl()) - ->internal::template CacheBaseImpl< - typename CacheStore::State, - CacheStore>::InitArcIterator(s_, &cache_data_); - num_arcs_ = cache_data_.narcs; - arcs_ = cache_data_.arcs; // arcs_ is a pointer to the cached arcs. - data_flags_ = kArcValueFlags; // All the arc member values are valid. - } else { // Otherwise delay decision until Value() is called. - tuple_ = fst_.GetImpl()->GetStateTable()->Tuple(s_); - if (tuple_.fst_state == kNoStateId) { - num_arcs_ = 0; - } else { - // The decision to cache or not to cache has been defered until Value() - // or - // SetFlags() is called. However, the arc iterator is set up now to be - // ready for non-caching in order to keep the Value() method simple and - // efficient. - const auto *rfst = fst_.GetImpl()->GetFst(tuple_.fst_id); - rfst->InitArcIterator(tuple_.fst_state, &local_data_); - // arcs_ is a pointer to the arcs in the underlying machine. - arcs_ = local_data_.arcs; - // Computes the final arc (but not its destination state) if a final arc - // is required. - bool has_final_arc = fst_.GetMutableImpl()->ComputeFinalArc( - tuple_, &final_arc_, kArcValueFlags & ~kArcNextStateValue); - // Sets the arc value flags that hold for final_arc_. - final_flags_ = kArcValueFlags & ~kArcNextStateValue; - // Computes the number of arcs. - num_arcs_ = local_data_.narcs; - if (has_final_arc) ++num_arcs_; - // Sets the offset between the underlying arc positions and the - // positions - // in the arc iterator. - offset_ = num_arcs_ - local_data_.narcs; - // Defers the decision to cache or not until Value() or SetFlags() is - // called. - data_flags_ = 0; - } - } - } - - ~ArcIterator() { - if (cache_data_.ref_count) --(*cache_data_.ref_count); - if (local_data_.ref_count) --(*local_data_.ref_count); - } - - void ExpandAndCache() const { - // TODO(allauzen): revisit this. - // fst_.GetImpl()->Expand(s_, tuple_, local_data_); - // (fst_.GetImpl())->CacheImpl*>::InitArcIterator(s_, - // &cache_data_); - // - fst_.InitArcIterator(s_, &cache_data_); // Expand and cache state. - arcs_ = cache_data_.arcs; // arcs_ is a pointer to the cached arcs. - data_flags_ = kArcValueFlags; // All the arc member values are valid. - offset_ = 0; // No offset. - } - - void Init() { - if (flags_ & kArcNoCache) { // If caching is disabled - // arcs_ is a pointer to the arcs in the underlying machine. - arcs_ = local_data_.arcs; - // Sets the arcs value flags that hold for arcs_. - data_flags_ = kArcWeightValue; - if (!fst_.GetMutableImpl()->EpsilonOnCallInput()) { - data_flags_ |= kArcILabelValue; - } - // Sets the offset between the underlying arc positions and the positions - // in the arc iterator. - offset_ = num_arcs_ - local_data_.narcs; - } else { - ExpandAndCache(); - } - } - - bool Done() const { return pos_ >= num_arcs_; } - - const Arc &Value() const { - // If data_flags_ is 0, non-caching was not requested. - if (!data_flags_) { - // TODO(allauzen): Revisit this. - if (flags_ & kArcNoCache) { - // Should never happen. - FSTERROR() << "ReplaceFst: Inconsistent arc iterator flags"; - } - ExpandAndCache(); - } - if (pos_ - offset_ >= 0) { // The requested arc is not the final arc. - const auto &arc = arcs_[pos_ - offset_]; - if ((data_flags_ & flags_) == (flags_ & kArcValueFlags)) { - // If the value flags match the recquired value flags then returns the - // arc. - return arc; - } else { - // Otherwise, compute the corresponding arc on-the-fly. - fst_.GetMutableImpl()->ComputeArc(tuple_, arc, &arc_, - flags_ & kArcValueFlags); - return arc_; - } - } else { // The requested arc is the final arc. - if ((final_flags_ & flags_) != (flags_ & kArcValueFlags)) { - // If the arc value flags that hold for the final arc do not match the - // requested value flags, then - // final_arc_ needs to be updated. - fst_.GetMutableImpl()->ComputeFinalArc(tuple_, &final_arc_, - flags_ & kArcValueFlags); - final_flags_ = flags_ & kArcValueFlags; - } - return final_arc_; - } - } - - void Next() { ++pos_; } - - size_t Position() const { return pos_; } - - void Reset() { pos_ = 0; } - - void Seek(size_t pos) { pos_ = pos; } - - uint8_t Flags() const { return flags_; } - - void SetFlags(uint8_t flags, uint8_t mask) { - // Updates the flags taking into account what flags are supported - // by the FST. - flags_ &= ~mask; - flags_ |= (flags & fst_.GetImpl()->ArcIteratorFlags()); - // If non-caching is not requested (and caching has not already been - // performed), then flush data_flags_ to request caching during the next - // call to Value(). - if (!(flags_ & kArcNoCache) && data_flags_ != kArcValueFlags) { - if (!fst_.GetImpl()->HasArcs(s_)) data_flags_ = 0; - } - // If data_flags_ has been flushed but non-caching is requested before - // calling Value(), then set up the iterator for non-caching. - if ((flags & kArcNoCache) && (!data_flags_)) Init(); - } - - private: - const ReplaceFst &fst_; // Reference to the FST. - StateId s_; // State in the FST. - mutable StateTuple tuple_; // Tuple corresponding to state_. - - ssize_t pos_; // Current position. - mutable ssize_t offset_; // Offset between position in iterator and in arcs_. - ssize_t num_arcs_; // Number of arcs at state_. - uint8_t flags_; // Behavorial flags for the arc iterator - mutable Arc arc_; // Memory to temporarily store computed arcs. - - mutable ArcIteratorData cache_data_; // Arc iterator data in cache. - mutable ArcIteratorData local_data_; // Arc iterator data in local FST. - - mutable const Arc *arcs_; // Array of arcs. - mutable uint8_t data_flags_; // Arc value flags valid for data in arcs_. - mutable Arc final_arc_; // Final arc (when required). - mutable uint8_t final_flags_; // Arc value flags valid for final_arc_. - - ArcIterator(const ArcIterator &) = delete; - ArcIterator &operator=(const ArcIterator &) = delete; -}; - -template -class ReplaceFstMatcher : public MatcherBase { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FST = ReplaceFst; - using LocalMatcher = MultiEpsMatcher>>; - - using StateTuple = typename StateTable::StateTuple; - - // This makes a copy of the FST. - ReplaceFstMatcher(const ReplaceFst &fst, - MatchType match_type) - : owned_fst_(fst.Copy()), - fst_(*owned_fst_), - impl_(fst_.GetMutableImpl()), - s_(fst::kNoStateId), - match_type_(match_type), - current_loop_(false), - final_arc_(false), - loop_(kNoLabel, 0, Weight::One(), kNoStateId) { - if (match_type_ == fst::MATCH_OUTPUT) { - std::swap(loop_.ilabel, loop_.olabel); - } - InitMatchers(); - } - - // This doesn't copy the FST. - ReplaceFstMatcher(const ReplaceFst *fst, - MatchType match_type) - : fst_(*fst), - impl_(fst_.GetMutableImpl()), - s_(fst::kNoStateId), - match_type_(match_type), - current_loop_(false), - final_arc_(false), - loop_(kNoLabel, 0, Weight::One(), kNoStateId) { - if (match_type_ == fst::MATCH_OUTPUT) { - std::swap(loop_.ilabel, loop_.olabel); - } - InitMatchers(); - } - - // This makes a copy of the FST. - ReplaceFstMatcher(const ReplaceFstMatcher &matcher, bool safe = false) - : owned_fst_(matcher.fst_.Copy(safe)), - fst_(*owned_fst_), - impl_(fst_.GetMutableImpl()), - s_(fst::kNoStateId), - match_type_(matcher.match_type_), - current_loop_(false), - final_arc_(false), - loop_(fst::kNoLabel, 0, Weight::One(), fst::kNoStateId) { - if (match_type_ == fst::MATCH_OUTPUT) { - std::swap(loop_.ilabel, loop_.olabel); - } - InitMatchers(); - } - - // Creates a local matcher for each component FST in the RTN. LocalMatcher is - // a multi-epsilon wrapper matcher. MultiEpsilonMatcher is used to match each - // non-terminal arc, since these non-terminal - // turn into epsilons on recursion. - void InitMatchers() { - const auto &fst_array = impl_->fst_array_; - matcher_.resize(fst_array.size()); - for (Label i = 0; i < fst_array.size(); ++i) { - if (fst_array[i]) { - matcher_[i] = std::make_unique(*fst_array[i], match_type_, - kMultiEpsList); - auto it = impl_->nonterminal_set_.begin(); - for (; it != impl_->nonterminal_set_.end(); ++it) { - matcher_[i]->AddMultiEpsLabel(*it); - } - } - } - } - - ReplaceFstMatcher *Copy(bool safe = false) const override { - return new ReplaceFstMatcher(*this, safe); - } - - MatchType Type(bool test) const override { - if (match_type_ == MATCH_NONE) return match_type_; - const auto true_prop = - match_type_ == MATCH_INPUT ? kILabelSorted : kOLabelSorted; - const auto false_prop = - match_type_ == MATCH_INPUT ? kNotILabelSorted : kNotOLabelSorted; - const auto props = fst_.Properties(true_prop | false_prop, test); - if (props & true_prop) { - return match_type_; - } else if (props & false_prop) { - return MATCH_NONE; - } else { - return MATCH_UNKNOWN; - } - } - - const Fst &GetFst() const override { return fst_; } - - uint64_t Properties(uint64_t props) const override { return props; } - - // Sets the state from which our matching happens. - void SetState(StateId s) final { - if (s_ == s) return; - s_ = s; - tuple_ = impl_->GetStateTable()->Tuple(s_); - if (tuple_.fst_state == kNoStateId) { - done_ = true; - return; - } - // Gets current matcher, used for non-epsilon matching. - current_matcher_ = matcher_[tuple_.fst_id].get(); - current_matcher_->SetState(tuple_.fst_state); - loop_.nextstate = s_; - final_arc_ = false; - } - - // Searches for label from previous set state. If label == 0, first - // hallucinate an epsilon loop; otherwise use the underlying matcher to - // search for the label or epsilons. Note since the ReplaceFst recursion - // on non-terminal arcs causes epsilon transitions to be created we use - // MultiEpsilonMatcher to search for possible matches of non-terminals. If the - // component FST - // reaches a final state we also need to add the exiting final arc. - bool Find(Label label) final { - bool found = false; - label_ = label; - if (label_ == 0 || label_ == kNoLabel) { - // Computes loop directly, avoiding Replace::ComputeArc. - if (label_ == 0) { - current_loop_ = true; - found = true; - } - // Searches for matching multi-epsilons. - final_arc_ = impl_->ComputeFinalArc(tuple_, nullptr); - found = current_matcher_->Find(kNoLabel) || final_arc_ || found; - } else { - // Searches on a sub machine directly using sub machine matcher. - found = current_matcher_->Find(label_); - } - return found; - } - - bool Done() const final { - return !current_loop_ && !final_arc_ && current_matcher_->Done(); - } - - const Arc &Value() const final { - if (current_loop_) return loop_; - if (final_arc_) { - impl_->ComputeFinalArc(tuple_, &arc_); - return arc_; - } - const auto &component_arc = current_matcher_->Value(); - impl_->ComputeArc(tuple_, component_arc, &arc_); - return arc_; - } - - void Next() final { - if (current_loop_) { - current_loop_ = false; - return; - } - if (final_arc_) { - final_arc_ = false; - return; - } - current_matcher_->Next(); - } - - ssize_t Priority(StateId s) final { return fst_.NumArcs(s); } - - private: - std::unique_ptr> owned_fst_; - const ReplaceFst &fst_; - internal::ReplaceFstImpl *impl_; - LocalMatcher *current_matcher_; - std::vector> matcher_; - StateId s_; // Current state. - Label label_; // Current label. - MatchType match_type_; // Supplied by caller. - mutable bool done_; - mutable bool current_loop_; // Current arc is the implicit loop. - mutable bool final_arc_; // Current arc for exiting recursion. - mutable StateTuple tuple_; // Tuple corresponding to state_. - mutable Arc arc_; - Arc loop_; - - ReplaceFstMatcher &operator=(const ReplaceFstMatcher &) = delete; -}; - -template -inline void ReplaceFst::InitStateIterator( - StateIteratorData *data) const { - data->base = - std::make_unique>>( - *this); -} - -using StdReplaceFst = ReplaceFst; - -// Recursively replaces arcs in the root FSTs with other FSTs. -// This version writes the result of replacement to an output MutableFst. -// -// Replace supports replacement of arcs in one Fst with another FST. This -// replacement is recursive. Replace takes an array of FST(s). One FST -// represents the root (or topology) machine. The root FST refers to other FSTs -// by recursively replacing arcs labeled as non-terminals with the matching -// non-terminal FST. Currently Replace uses the output symbols of the arcs to -// determine whether the arc is a non-terminal arc or not. A non-terminal can be -// any label that is not a non-zero terminal label in the output alphabet. -// -// Note that input argument is a vector of pairs. These correspond to the tuple -// of non-terminal Label and corresponding FST. -template -void Replace(const std::vector *>> - &ifst_array, - MutableFst *ofst, - ReplaceFstOptions opts = ReplaceFstOptions()) { - opts.gc = true; - opts.gc_limit = 0; // Caches only the last state for fastest copy. - *ofst = ReplaceFst(ifst_array, opts); -} - -template -void Replace(const std::vector *>> - &ifst_array, - MutableFst *ofst, const ReplaceUtilOptions &opts) { - Replace(ifst_array, ofst, ReplaceFstOptions(opts)); -} - -// For backwards compatibility. -template -void Replace(const std::vector *>> - &ifst_array, - MutableFst *ofst, typename Arc::Label root, - bool epsilon_on_replace) { - Replace(ifst_array, ofst, ReplaceFstOptions(root, epsilon_on_replace)); -} - -template -void Replace(const std::vector *>> - &ifst_array, - MutableFst *ofst, typename Arc::Label root) { - Replace(ifst_array, ofst, ReplaceFstOptions(root)); -} - -} // namespace fst - -#endif // FST_REPLACE_H_ diff --git a/contrib/fstlib/fst/reverse.h b/contrib/fstlib/fst/reverse.h deleted file mode 100644 index b47df1c..0000000 --- a/contrib/fstlib/fst/reverse.h +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to sort arcs in an FST. - -#ifndef FST_REVERSE_H_ -#define FST_REVERSE_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Reverses an FST. The reversed result is written to an output mutable FST. -// If A transduces string x to y with weight a, then the reverse of A -// transduces the reverse of x to the reverse of y with weight a.Reverse(). -// -// Typically, a = a.Reverse() and an arc is its own reverse (e.g., for -// TropicalWeight or LogWeight). In general, e.g., when the weights only form a -// left or right semiring, the output arc type must match the input arc type -// except having the reversed Weight type. -// -// When require_superinitial is false, a superinitial state is not created in -// the reversed FST iff the input FST has exactly one final state (which becomes -// the initial state of the reversed FST) with a final weight of semiring One, -// or if it does not belong to any cycle. When require_superinitial is true, a -// superinitial state is always created. -template -void Reverse(const Fst &ifst, MutableFst *ofst, - bool require_superinitial = true) { - using StateId = typename FromArc::StateId; - using Weight = typename FromArc::Weight; - ofst->DeleteStates(); - ofst->SetInputSymbols(ifst.InputSymbols()); - ofst->SetOutputSymbols(ifst.OutputSymbols()); - if (std::optional num_states = ifst.NumStatesIfKnown()) { - ofst->ReserveStates(*num_states + 1); - } - StateId istart = ifst.Start(); - StateId ostart = kNoStateId; - StateId offset = 0; - uint64_t dfs_iprops = 0; - uint64_t dfs_oprops = 0; - if (!require_superinitial) { - for (StateIterator> siter(ifst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - if (ifst.Final(s) == Weight::Zero()) continue; - if (ostart != kNoStateId) { - ostart = kNoStateId; - break; - } else { - ostart = s; - } - } - if (ostart != kNoStateId && ifst.Final(ostart) != Weight::One()) { - std::vector scc; - SccVisitor scc_visitor(&scc, nullptr, nullptr, &dfs_iprops); - DfsVisit(ifst, &scc_visitor); - if (std::count(scc.begin(), scc.end(), scc[ostart]) > 1) { - ostart = kNoStateId; - } else { - for (ArcIterator> aiter(ifst, ostart); !aiter.Done(); - aiter.Next()) { - if (aiter.Value().nextstate == ostart) { - ostart = kNoStateId; - break; - } - } - } - if (ostart != kNoStateId) dfs_oprops = kInitialAcyclic; - } - } - if (ostart == kNoStateId) { // Super-initial requested or needed. - ostart = ofst->AddState(); - offset = 1; - } - for (StateIterator> siter(ifst); !siter.Done(); siter.Next()) { - const auto is = siter.Value(); - const auto os = is + offset; - while (ofst->NumStates() <= os) ofst->AddState(); - if (is == istart) ofst->SetFinal(os); - const auto weight = ifst.Final(is); - if ((weight != Weight::Zero()) && (offset == 1)) { - const ToArc oarc(0, 0, weight.Reverse(), os); - ofst->AddArc(0, oarc); - } - for (ArcIterator> aiter(ifst, is); !aiter.Done(); - aiter.Next()) { - const auto &iarc = aiter.Value(); - const auto nos = iarc.nextstate + offset; - auto weight = iarc.weight.Reverse(); - if (!offset && (nos == ostart)) { - weight = Times(ifst.Final(ostart).Reverse(), weight); - } - const ToArc oarc(iarc.ilabel, iarc.olabel, weight, os); - while (ofst->NumStates() <= nos) ofst->AddState(); - ofst->AddArc(nos, oarc); - } - } - ofst->SetStart(ostart); - if (offset == 0 && ostart == istart) { - ofst->SetFinal(ostart, ifst.Final(ostart).Reverse()); - } - const auto iprops = ifst.Properties(kCopyProperties, false) | dfs_iprops; - const auto oprops = ofst->Properties(kFstProperties, false) | dfs_oprops; - ofst->SetProperties(ReverseProperties(iprops, offset == 1) | oprops, - kFstProperties); -} - -} // namespace fst - -#endif // FST_REVERSE_H_ diff --git a/contrib/fstlib/fst/reweight.h b/contrib/fstlib/fst/reweight.h deleted file mode 100644 index a2ac784..0000000 --- a/contrib/fstlib/fst/reweight.h +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function to reweight an FST. - -#ifndef FST_REWEIGHT_H_ -#define FST_REWEIGHT_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace fst { - -enum ReweightType { REWEIGHT_TO_INITIAL, REWEIGHT_TO_FINAL }; - -// Reweights an FST according to a vector of potentials in a given direction. -// The weight must be left distributive when reweighting towards the initial -// state and right distributive when reweighting towards the final states. -// -// An arc of weight w, with an origin state of potential p and destination state -// of potential q, is reweighted by p^-1 \otimes (w \otimes q) when reweighting -// torwards the initial state, and by (p \otimes w) \otimes q^-1 when -// reweighting towards the final states. -template -void Reweight(MutableFst *fst, - const std::vector &potential, - ReweightType type) { - using Weight = typename Arc::Weight; - if (fst->NumStates() == 0) return; - // TODO(kbg): Make this a compile-time static_assert once we have a pleasant - // way to "deregister" this operation for non-distributive semirings so an - // informative error message is produced. - if (type == REWEIGHT_TO_FINAL && !(Weight::Properties() & kRightSemiring)) { - FSTERROR() << "Reweight: Reweighting to the final states requires " - << "Weight to be right distributive: " << Weight::Type(); - fst->SetProperties(kError, kError); - return; - } - // TODO(kbg): Make this a compile-time static_assert once we have a pleasant - // way to "deregister" this operation for non-distributive semirings so an - // informative error message is produced. - if (type == REWEIGHT_TO_INITIAL && !(Weight::Properties() & kLeftSemiring)) { - FSTERROR() << "Reweight: Reweighting to the initial state requires " - << "Weight to be left distributive: " << Weight::Type(); - fst->SetProperties(kError, kError); - return; - } - const uint64_t input_props = fst->Properties(kFstProperties, false); - StateIterator> siter(*fst); - for (; !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - if (s == potential.size()) break; - const auto &weight = potential[s]; - if (weight != Weight::Zero()) { - for (MutableArcIterator> aiter(fst, s); !aiter.Done(); - aiter.Next()) { - auto arc = aiter.Value(); - if (arc.nextstate >= potential.size()) continue; - const auto &nextweight = potential[arc.nextstate]; - if (nextweight == Weight::Zero()) continue; - if (type == REWEIGHT_TO_INITIAL) { - arc.weight = - Divide(Times(arc.weight, nextweight), weight, DIVIDE_LEFT); - } - if (type == REWEIGHT_TO_FINAL) { - arc.weight = - Divide(Times(weight, arc.weight), nextweight, DIVIDE_RIGHT); - } - aiter.SetValue(arc); - } - if (type == REWEIGHT_TO_INITIAL) { - fst->SetFinal(s, Divide(fst->Final(s), weight, DIVIDE_LEFT)); - } - } - if (type == REWEIGHT_TO_FINAL) { - fst->SetFinal(s, Times(weight, fst->Final(s))); - } - } - // This handles elements past the end of the potentials array. - for (; !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - if (type == REWEIGHT_TO_FINAL) { - fst->SetFinal(s, Times(Weight::Zero(), fst->Final(s))); - } - } - const auto startweight = fst->Start() < potential.size() - ? potential[fst->Start()] - : Weight::Zero(); - bool added_start_epsilon = false; - if ((startweight != Weight::One()) && (startweight != Weight::Zero())) { - if (fst->Properties(kInitialAcyclic, true) & kInitialAcyclic) { - const auto s = fst->Start(); - for (MutableArcIterator> aiter(fst, s); !aiter.Done(); - aiter.Next()) { - auto arc = aiter.Value(); - if (type == REWEIGHT_TO_INITIAL) { - arc.weight = Times(startweight, arc.weight); - } else { - arc.weight = Times(Divide(Weight::One(), startweight, DIVIDE_RIGHT), - arc.weight); - } - aiter.SetValue(arc); - } - if (type == REWEIGHT_TO_INITIAL) { - fst->SetFinal(s, Times(startweight, fst->Final(s))); - } else { - fst->SetFinal(s, Times(Divide(Weight::One(), startweight, DIVIDE_RIGHT), - fst->Final(s))); - } - } else { - const auto s = fst->AddState(); - const auto weight = - (type == REWEIGHT_TO_INITIAL) - ? startweight - : Divide(Weight::One(), startweight, DIVIDE_RIGHT); - fst->AddArc(s, Arc(0, 0, weight, fst->Start())); - fst->SetStart(s); - added_start_epsilon = true; - } - } - fst->SetProperties(ReweightProperties(input_props, added_start_epsilon) | - fst->Properties(kFstProperties, false), - kFstProperties); -} - -} // namespace fst - -#endif // FST_REWEIGHT_H_ diff --git a/contrib/fstlib/fst/rmepsilon.h b/contrib/fstlib/fst/rmepsilon.h deleted file mode 100644 index ca1f2aa..0000000 --- a/contrib/fstlib/fst/rmepsilon.h +++ /dev/null @@ -1,580 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes that implemement epsilon-removal. - -#ifndef FST_RMEPSILON_H_ -#define FST_RMEPSILON_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -template -struct RmEpsilonOptions - : public ShortestDistanceOptions> { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - bool connect; // Connect output - Weight weight_threshold; // Pruning weight threshold. - StateId state_threshold; // Pruning state threshold. - - explicit RmEpsilonOptions(Queue *queue, float delta = kShortestDelta, - bool connect = true, - Weight weight_threshold = Weight::Zero(), - StateId state_threshold = kNoStateId) - : ShortestDistanceOptions>( - queue, EpsilonArcFilter(), kNoStateId, delta), - connect(connect), - weight_threshold(std::move(weight_threshold)), - state_threshold(state_threshold) {} -}; - -namespace internal { - -// Computation state of the epsilon-removal algorithm. -template -class RmEpsilonState { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - RmEpsilonState(const Fst &fst, std::vector *distance, - const RmEpsilonOptions &opts) - : fst_(fst), - distance_(distance), - sd_state_(fst_, distance, opts, true), - expand_id_(0) {} - - void Expand(StateId s); - - std::vector &Arcs() { return arcs_; } - - const Weight &Final() const { return final_weight_; } - - bool Error() const { return sd_state_.Error(); } - - private: - struct Element { - Label ilabel; - Label olabel; - StateId nextstate; - - Element() = default; - - Element(Label ilabel, Label olabel, StateId nexstate) - : ilabel(ilabel), olabel(olabel), nextstate(nexstate) {} - }; - - struct ElementHash { - public: - size_t operator()(const Element &element) const { - static constexpr size_t prime0 = 7853; - static constexpr size_t prime1 = 7867; - return static_cast(element.nextstate) + - static_cast(element.ilabel) * prime0 + - static_cast(element.olabel) * prime1; - } - }; - - class ElementEqual { - public: - bool operator()(const Element &e1, const Element &e2) const { - return (e1.ilabel == e2.ilabel) && (e1.olabel == e2.olabel) && - (e1.nextstate == e2.nextstate); - } - }; - - using ElementMap = std::unordered_map, - ElementHash, ElementEqual>; - - const Fst &fst_; - // Distance from state being expanded in epsilon-closure. - std::vector *distance_; - // Shortest distance algorithm computation state. - internal::ShortestDistanceState> sd_state_; - // Maps an element to a pair corresponding to a position in the arcs vector - // of the state being expanded. The element corresopnds to the position in - // the arcs_ vector if p.first is equal to the state being expanded. - ElementMap element_map_; - EpsilonArcFilter eps_filter_; - std::stack> - eps_queue_; // Queue used to visit the epsilon-closure. - std::vector visited_; // True if the state has been visited. - std::vector visited_states_; // List of visited states. - std::vector arcs_; // Arcs of state being expanded. - Weight final_weight_; // Final weight of state being expanded. - StateId expand_id_; // Unique ID for each call to Expand - - RmEpsilonState(const RmEpsilonState &) = delete; - RmEpsilonState &operator=(const RmEpsilonState &) = delete; -}; - -template -void RmEpsilonState::Expand(typename Arc::StateId source) { - final_weight_ = Weight::Zero(); - arcs_.clear(); - sd_state_.ShortestDistance(source); - if (sd_state_.Error()) return; - eps_queue_.push(source); - while (!eps_queue_.empty()) { - const auto state = eps_queue_.top(); - eps_queue_.pop(); - if (static_cast(visited_.size()) <= state) { - visited_.resize(state + 1, false); - } - if (visited_[state]) continue; - visited_[state] = true; - visited_states_.push_back(state); - for (ArcIterator> aiter(fst_, state); !aiter.Done(); - aiter.Next()) { - auto arc = aiter.Value(); - arc.weight = Times((*distance_)[state], arc.weight); - if (eps_filter_(arc)) { - if (static_cast(visited_.size()) <= - arc.nextstate) { - visited_.resize(arc.nextstate + 1, false); - } - if (!visited_[arc.nextstate]) eps_queue_.push(arc.nextstate); - } else if (auto [insert_it, success] = element_map_.emplace( - Element(arc.ilabel, arc.olabel, arc.nextstate), - std::make_pair(expand_id_, arcs_.size())); - success) { - arcs_.push_back(std::move(arc)); - } else if (auto &[xid, arc_idx] = insert_it->second; xid == expand_id_) { - auto &weight = arcs_[arc_idx].weight; - weight = Plus(weight, arc.weight); - } else { - xid = expand_id_; - arc_idx = arcs_.size(); - arcs_.push_back(std::move(arc)); - } - } - final_weight_ = - Plus(final_weight_, Times((*distance_)[state], fst_.Final(state))); - } - - for (const auto state_id : visited_states_) visited_[state_id] = false; - visited_states_.clear(); - ++expand_id_; -} - -} // namespace internal - -// Removes epsilon-transitions (when both the input and output label are an -// epsilon) from a transducer. The result will be an equivalent FST that has no -// such epsilon transitions. This version modifies its input. It allows fine -// control via the options argument; see below for a simpler interface. -// -// The distance vector will be used to hold the shortest distances during the -// epsilon-closure computation. The state queue discipline and convergence delta -// are taken in the options argument. -template -void RmEpsilon(MutableFst *fst, - std::vector *distance, - const RmEpsilonOptions &opts) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - if (fst->Start() == kNoStateId) return; - // noneps_in[s] will be set to true iff s admits a non-epsilon incoming - // transition or is the start state. - std::vector noneps_in(fst->NumStates(), false); - noneps_in[fst->Start()] = true; - for (size_t i = 0; i < fst->NumStates(); ++i) { - for (ArcIterator> aiter(*fst, i); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - if (arc.ilabel != 0 || arc.olabel != 0) { - noneps_in[arc.nextstate] = true; - } - } - } - // States sorted in topological order when (acyclic) or generic topological - // order (cyclic). - std::vector states; - states.reserve(fst->NumStates()); - if (fst->Properties(kTopSorted, false) & kTopSorted) { - for (size_t i = 0; i < fst->NumStates(); i++) states.push_back(i); - } else if (fst->Properties(kAcyclic, false) & kAcyclic) { - std::vector order; - bool acyclic; - TopOrderVisitor top_order_visitor(&order, &acyclic); - DfsVisit(*fst, &top_order_visitor, EpsilonArcFilter()); - // Sanity check: should be acyclic if property bit is set. - if (!acyclic) { - FSTERROR() << "RmEpsilon: Inconsistent acyclic property bit"; - fst->SetProperties(kError, kError); - return; - } - states.resize(order.size()); - for (StateId i = 0; i < order.size(); i++) states[order[i]] = i; - } else { - uint64_t props; - std::vector scc; - SccVisitor scc_visitor(&scc, nullptr, nullptr, &props); - DfsVisit(*fst, &scc_visitor, EpsilonArcFilter()); - std::vector first(scc.size(), kNoStateId); - std::vector next(scc.size(), kNoStateId); - for (StateId i = 0; i < scc.size(); i++) { - if (first[scc[i]] != kNoStateId) next[i] = first[scc[i]]; - first[scc[i]] = i; - } - for (StateId i = 0; i < first.size(); i++) { - for (auto j = first[i]; j != kNoStateId; j = next[j]) { - states.push_back(j); - } - } - } - internal::RmEpsilonState rmeps_state(*fst, distance, opts); - while (!states.empty()) { - const auto state = states.back(); - states.pop_back(); - if (!noneps_in[state] && - (opts.connect || opts.weight_threshold != Weight::Zero() || - opts.state_threshold != kNoStateId)) { - continue; - } - rmeps_state.Expand(state); - fst->SetFinal(state, rmeps_state.Final()); - fst->DeleteArcs(state); - auto &arcs = rmeps_state.Arcs(); - fst->ReserveArcs(state, arcs.size()); - while (!arcs.empty()) { - fst->AddArc(state, arcs.back()); - arcs.pop_back(); - } - } - if (opts.connect || opts.weight_threshold != Weight::Zero() || - opts.state_threshold != kNoStateId) { - for (size_t s = 0; s < fst->NumStates(); ++s) { - if (!noneps_in[s]) fst->DeleteArcs(s); - } - } - if (rmeps_state.Error()) fst->SetProperties(kError, kError); - fst->SetProperties( - RmEpsilonProperties(fst->Properties(kFstProperties, false)), - kFstProperties); - if (opts.weight_threshold != Weight::Zero() || - opts.state_threshold != kNoStateId) { - if constexpr (IsPath::value) { - Prune(fst, opts.weight_threshold, opts.state_threshold); - } else { - FSTERROR() << "RmEpsilon: Weight must have path property: " - << Weight::Type(); - fst->SetProperties(kError, kError); - return; - } - } - if (opts.connect && opts.weight_threshold == Weight::Zero() && - opts.state_threshold == kNoStateId) { - Connect(fst); - } -} - -// Removes epsilon-transitions (when both the input and output label -// are an epsilon) from a transducer. The result will be an equivalent -// FST that has no such epsilon transitions. This version modifies its -// input. It has a simplified interface; see above for a version that -// allows finer control. -// -// Complexity: -// -// - Time: -// -// Unweighted: O(v^2 + ve). -// Acyclic: O(v^2 + V e). -// Tropical semiring: O(v^2 log V + ve). -// General: exponential. -// -// - Space: O(vE) -// -// where v is the number of states visited and e is the number of arcs visited. -// -// For more information, see: -// -// Mohri, M. 2002. Generic epsilon-removal and input epsilon-normalization -// algorithms for weighted transducers. International Journal of Computer -// Science 13(1): 129-143. -template -void RmEpsilon(MutableFst *fst, bool connect = true, - typename Arc::Weight weight_threshold = Arc::Weight::Zero(), - typename Arc::StateId state_threshold = kNoStateId, - float delta = kShortestDelta) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - std::vector distance; - AutoQueue state_queue(*fst, &distance, EpsilonArcFilter()); - RmEpsilonOptions> opts( - &state_queue, delta, connect, weight_threshold, state_threshold); - RmEpsilon(fst, &distance, opts); -} - -struct RmEpsilonFstOptions : CacheOptions { - float delta; - - explicit RmEpsilonFstOptions(const CacheOptions &opts, - float delta = kShortestDelta) - : CacheOptions(opts), delta(delta) {} - - explicit RmEpsilonFstOptions(float delta = kShortestDelta) : delta(delta) {} -}; - -namespace internal { - -// Implementation of delayed RmEpsilonFst. -template -class RmEpsilonFstImpl : public CacheImpl { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Store = DefaultCacheStore; - using State = typename Store::State; - - using FstImpl::Properties; - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheBaseImpl>::HasArcs; - using CacheBaseImpl>::HasFinal; - using CacheBaseImpl>::HasStart; - using CacheBaseImpl>::PushArc; - using CacheBaseImpl>::SetArcs; - using CacheBaseImpl>::SetFinal; - using CacheBaseImpl>::SetStart; - - RmEpsilonFstImpl(const Fst &fst, const RmEpsilonFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - delta_(opts.delta), - rmeps_state_( - *fst_, &distance_, - RmEpsilonOptions>(&queue_, delta_, false)) { - SetType("rmepsilon"); - SetProperties( - RmEpsilonProperties(fst.Properties(kFstProperties, false), true), - kCopyProperties); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - } - - RmEpsilonFstImpl(const RmEpsilonFstImpl &impl) - : CacheImpl(impl), - fst_(impl.fst_->Copy(true)), - delta_(impl.delta_), - rmeps_state_( - *fst_, &distance_, - RmEpsilonOptions>(&queue_, delta_, false)) { - SetType("rmepsilon"); - SetProperties(impl.Properties(), kCopyProperties); - SetInputSymbols(impl.InputSymbols()); - SetOutputSymbols(impl.OutputSymbols()); - } - - StateId Start() { - if (!HasStart()) SetStart(fst_->Start()); - return CacheImpl::Start(); - } - - Weight Final(StateId s) { - if (!HasFinal(s)) Expand(s); - return CacheImpl::Final(s); - } - - size_t NumArcs(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumArcs(s); - } - - size_t NumInputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumInputEpsilons(s); - } - - size_t NumOutputEpsilons(StateId s) { - if (!HasArcs(s)) Expand(s); - return CacheImpl::NumOutputEpsilons(s); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - // Sets error if found and returns other FST impl properties. - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && - (fst_->Properties(kError, false) || rmeps_state_.Error())) { - SetProperties(kError, kError); - } - return FstImpl::Properties(mask); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) { - if (!HasArcs(s)) Expand(s); - CacheImpl::InitArcIterator(s, data); - } - - void Expand(StateId s) { - rmeps_state_.Expand(s); - SetFinal(s, rmeps_state_.Final()); - auto &arcs = rmeps_state_.Arcs(); - while (!arcs.empty()) { - PushArc(s, std::move(arcs.back())); - arcs.pop_back(); - } - SetArcs(s); - } - - private: - std::unique_ptr> fst_; - float delta_; - std::vector distance_; - FifoQueue queue_; - internal::RmEpsilonState> rmeps_state_; -}; - -} // namespace internal - -// Removes epsilon-transitions (when both the input and output label are an -// epsilon) from a transducer. The result will be an equivalent FST that has no -// such epsilon transitions. This version is a -// delayed FST. -// -// Complexity: -// -// - Time: -// Unweighted: O(v^2 + ve). -// General: exponential. -// -// - Space: O(vE) -// -// where v is the number of states visited and e is the number of arcs visited. -// Constant time to visit an input state or arc is assumed and exclusive of -// caching. -// -// For more information, see: -// -// Mohri, M. 2002. Generic epsilon-removal and input epsilon-normalization -// algorithms for weighted transducers. International Journal of Computer -// Science 13(1): 129-143. -// -// This class attaches interface to implementation and handles -// reference counting, delegating most methods to ImplToFst. -template -class RmEpsilonFst : public ImplToFst> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using Store = DefaultCacheStore; - using State = typename Store::State; - using Impl = internal::RmEpsilonFstImpl; - - friend class ArcIterator>; - friend class StateIterator>; - - explicit RmEpsilonFst(const Fst &fst) - : ImplToFst(std::make_shared(fst, RmEpsilonFstOptions())) {} - - RmEpsilonFst(const Fst &fst, const RmEpsilonFstOptions &opts) - : ImplToFst(std::make_shared(fst, opts)) {} - - // See Fst<>::Copy() for doc. - RmEpsilonFst(const RmEpsilonFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Get a copy of this RmEpsilonFst. See Fst<>::Copy() for further doc. - RmEpsilonFst *Copy(bool safe = false) const override { - return new RmEpsilonFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - RmEpsilonFst &operator=(const RmEpsilonFst &) = delete; -}; - -// Specialization for RmEpsilonFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const RmEpsilonFst &fst) - : CacheStateIterator>(fst, fst.GetMutableImpl()) {} -}; - -// Specialization for RmEpsilonFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const RmEpsilonFst &fst, StateId s) - : CacheArcIterator>(fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void RmEpsilonFst::InitStateIterator( - StateIteratorData *data) const { - data->base = std::make_unique>>(*this); -} - -// Useful alias when using StdArc. -using StdRmEpsilonFst = RmEpsilonFst; - -} // namespace fst - -#endif // FST_RMEPSILON_H_ diff --git a/contrib/fstlib/fst/rmfinalepsilon.h b/contrib/fstlib/fst/rmfinalepsilon.h deleted file mode 100644 index 36dcdcc..0000000 --- a/contrib/fstlib/fst/rmfinalepsilon.h +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function to remove of final states that have epsilon-only input arcs. - -#ifndef FST_RMFINALEPSILON_H_ -#define FST_RMFINALEPSILON_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Removes final states that have epsilon-only input arcs. -template -void RmFinalEpsilon(MutableFst *fst) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - // Determines the coaccesibility of states. - std::vector access; - std::vector coaccess; - uint64_t props = 0; - SccVisitor scc_visitor(nullptr, &access, &coaccess, &props); - DfsVisit(*fst, &scc_visitor); - // Finds potential list of removable final states. These are final states that - // have no outgoing transitions or final states that have a non-coaccessible - // future. - std::unordered_set finals; - for (StateIterator> siter(*fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - if (fst->Final(s) != Weight::Zero()) { - bool future_coaccess = false; - for (ArcIterator> aiter(*fst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - if (coaccess[arc.nextstate]) { - future_coaccess = true; - break; - } - } - if (!future_coaccess) finals.insert(s); - } - } - // Moves the final weight. - std::vector arcs; - for (StateIterator> siter(*fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - auto weight = fst->Final(s); - arcs.clear(); - for (ArcIterator> aiter(*fst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - // Next state is in the list of finals. - if (finals.find(arc.nextstate) != finals.end()) { - // Sums up all epsilon arcs. - if (arc.ilabel == 0 && arc.olabel == 0) { - weight = Plus(Times(fst->Final(arc.nextstate), arc.weight), weight); - } else { - arcs.push_back(arc); - } - } else { - arcs.push_back(arc); - } - } - // If some arcs (epsilon arcs) were deleted, delete all arcs and add back - // only the non-epsilon arcs. - if (arcs.size() < fst->NumArcs(s)) { - fst->DeleteArcs(s); - fst->SetFinal(s, weight); - for (const auto &arc : arcs) fst->AddArc(s, arc); - } - } - Connect(fst); -} - -} // namespace fst - -#endif // FST_RMFINALEPSILON_H_ diff --git a/contrib/fstlib/fst/set-weight.h b/contrib/fstlib/fst/set-weight.h deleted file mode 100644 index 829e989..0000000 --- a/contrib/fstlib/fst/set-weight.h +++ /dev/null @@ -1,638 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Weights consisting of sets (of integral Labels) and -// associated semiring operation definitions using intersect -// and union. - -#ifndef FST_SET_WEIGHT_H_ -#define FST_SET_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -inline constexpr int kSetEmpty = 0; // Label for the empty set. -inline constexpr int kSetUniv = -1; // Label for the universal set. -inline constexpr int kSetBad = -2; // Label for a non-set. -inline constexpr char kSetSeparator = '_'; // Label separator in sets. - -// Determines whether to use (intersect, union) or (union, intersect) -// as (+, *) for the semiring. SET_INTERSECT_UNION_RESTRICTED is a -// restricted version of (intersect, union) that requires summed -// arguments to be equal (or an error is signalled), useful for -// algorithms that require a unique labelled path weight. SET_BOOLEAN -// treats all non-Zero() elements as equivalent (with Zero() == -// UnivSet()), useful for algorithms that don't really depend on the -// detailed sets. -enum SetType { - SET_INTERSECT_UNION = 0, - SET_UNION_INTERSECT = 1, - SET_INTERSECT_UNION_RESTRICT = 2, - SET_BOOLEAN = 3 -}; - -template -class SetWeightIterator; - -// Set semiring of integral labels. -template -class SetWeight { - public: - using Label = L; - using ReverseWeight = SetWeight; - using Iterator = SetWeightIterator; - friend class SetWeightIterator; - // Allow type-converting copy and move constructors private access. - template - friend class SetWeight; - - SetWeight() = default; - - // Input should be positive, sorted and unique. - template - SetWeight(const Iterator begin, const Iterator end) { - for (auto iter = begin; iter != end; ++iter) PushBack(*iter); - } - - // Input should be positive. (Non-positive value has - // special internal meaning w.r.t. integral constants above.) - explicit SetWeight(Label label) { PushBack(label); } - - template - explicit SetWeight(const SetWeight &w) - : first_(w.first_), rest_(w.rest_) {} - - template - explicit SetWeight(SetWeight &&w) - : first_(w.first_), rest_(std::move(w.rest_)) { - w.Clear(); - } - - template - SetWeight &operator=(const SetWeight &w) { - first_ = w.first_; - rest_ = w.rest_; - return *this; - } - - template - SetWeight &operator=(SetWeight &&w) { - first_ = w.first_; - rest_ = std::move(w.rest_); - w.Clear(); - return *this; - } - - static const SetWeight &Zero() { - return S == SET_UNION_INTERSECT ? EmptySet() : UnivSet(); - } - - static const SetWeight &One() { - return S == SET_UNION_INTERSECT ? UnivSet() : EmptySet(); - } - - static const SetWeight &NoWeight() { - static const auto *const no_weight = new SetWeight(Label(kSetBad)); - return *no_weight; - } - - static const std::string &Type() { - static const std::string *const type = - new std::string(S == SET_UNION_INTERSECT - ? "union_intersect_set" - : (S == SET_INTERSECT_UNION - ? "intersect_union_set" - : (S == SET_INTERSECT_UNION_RESTRICT - ? "restricted_set_intersect_union" - : "boolean_set"))); - return *type; - } - - bool Member() const; - - std::istream &Read(std::istream &strm); - - std::ostream &Write(std::ostream &strm) const; - - size_t Hash() const; - - SetWeight Quantize(float delta = kDelta) const { return *this; } - - ReverseWeight Reverse() const; - - static constexpr uint64_t Properties() { - return kIdempotent | kLeftSemiring | kRightSemiring | kCommutative; - } - - // These operations combined with the SetWeightIterator - // provide the access and mutation of the set internal elements. - - // The empty set. - static const SetWeight &EmptySet() { - static const auto *const empty = new SetWeight(Label(kSetEmpty)); - return *empty; - } - - // The univeral set. - static const SetWeight &UnivSet() { - static const auto *const univ = new SetWeight(Label(kSetUniv)); - return *univ; - } - - // Clear existing SetWeight. - void Clear() { - first_ = kSetEmpty; - rest_.clear(); - } - - size_t Size() const { return first_ == kSetEmpty ? 0 : rest_.size() + 1; } - - Label Back() { - if (rest_.empty()) { - return first_; - } else { - return rest_.back(); - } - } - - // Caller must add in sort order and be unique (or error signalled). - // Input should also be positive. Non-positive value (for the first - // push) has special internal meaning w.r.t. integral constants above. - void PushBack(Label label) { - if (first_ == kSetEmpty) { - first_ = label; - } else { - if (label <= Back() || label <= 0) { - FSTERROR() << "SetWeight: labels must be positive, added" - << " in sort order and be unique."; - rest_.push_back(Label(kSetBad)); - } - rest_.push_back(label); - } - } - - private: - Label first_ = kSetEmpty; // First label in set (kSetEmpty if empty). - std::list *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> 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 -void StateMap(MutableFst *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 -void StateMap(const Fst &ifst, MutableFst *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 (std::optional num_states = ifst.NumStatesIfKnown()) { - ofst->ReserveStates(*num_states); - } - for (StateIterator> siter(ifst); !siter.Done(); siter.Next()) { - ofst->AddState(); - } - ofst->SetStart(mapper->Start()); - for (StateIterator> 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 -void StateMap(const Fst &ifst, MutableFst *ofst, C mapper) { - StateMap(ifst, ofst, &mapper); -} - -using StateMapFstOptions = CacheOptions; - -template -class StateMapFst; - -// Facade around StateIteratorBase inheriting from StateIteratorBase. -template -class StateMapStateIteratorBase : public StateIteratorBase { - public: - using Arc = B; - using StateId = typename Arc::StateId; - - explicit StateMapStateIteratorBase(std::unique_ptr> base) - : base_(std::move(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> base_; - - StateMapStateIteratorBase() = delete; -}; - -namespace internal { - -// Implementation of delayed StateMapFst. -template -class StateMapFstImpl : public CacheImpl { - public: - using Arc = B; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - - using CacheImpl::PushArc; - using CacheImpl::HasArcs; - using CacheImpl::HasFinal; - using CacheImpl::HasStart; - using CacheImpl::SetArcs; - using CacheImpl::SetFinal; - using CacheImpl::SetStart; - - friend class StateIterator>; - - StateMapFstImpl(const Fst &fst, const C &mapper, - const StateMapFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - mapper_(new C(mapper, fst_.get())), - own_mapper_(true) { - Init(); - } - - StateMapFstImpl(const Fst &fst, C *mapper, const StateMapFstOptions &opts) - : CacheImpl(opts), - fst_(fst.Copy()), - mapper_(mapper), - own_mapper_(false) { - Init(); - } - - StateMapFstImpl(const StateMapFstImpl &impl) - : CacheImpl(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::Start(); - } - - Weight Final(StateId state) { - if (!HasFinal(state)) SetFinal(state, mapper_->Final(state)); - return CacheImpl::Final(state); - } - - size_t NumArcs(StateId state) { - if (!HasArcs(state)) Expand(state); - return CacheImpl::NumArcs(state); - } - - size_t NumInputEpsilons(StateId state) { - if (!HasArcs(state)) Expand(state); - return CacheImpl::NumInputEpsilons(state); - } - - size_t NumOutputEpsilons(StateId state) { - if (!HasArcs(state)) Expand(state); - return CacheImpl::NumOutputEpsilons(state); - } - - void InitStateIterator(StateIteratorData *datb) const { - StateIteratorData data; - fst_->InitStateIterator(&data); - datb->base = data.base ? std::make_unique>( - std::move(data.base)) - : nullptr; - datb->nstates = data.nstates; - } - - void InitArcIterator(StateId state, ArcIteratorData *data) { - if (!HasArcs(state)) Expand(state); - CacheImpl::InitArcIterator(state, data); - } - - uint64_t Properties() const override { return Properties(kFstProperties); } - - uint64_t Properties(uint64_t mask) const override { - if ((mask & kError) && (fst_->Properties(kError, false) || - (mapper_->Properties(0) & kError))) { - SetProperties(kError, kError); - } - return FstImpl::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 *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> 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 StateMapFst : public ImplToFst> { - public: - friend class ArcIterator>; - - using Arc = B; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - using Store = DefaultCacheStore; - using State = typename Store::State; - using Impl = internal::StateMapFstImpl; - - StateMapFst(const Fst &fst, const C &mapper, - const StateMapFstOptions &opts) - : ImplToFst(std::make_shared(fst, mapper, opts)) {} - - StateMapFst(const Fst &fst, C *mapper, const StateMapFstOptions &opts) - : ImplToFst(std::make_shared(fst, mapper, opts)) {} - - StateMapFst(const Fst &fst, const C &mapper) - : ImplToFst( - std::make_shared(fst, mapper, StateMapFstOptions())) {} - - StateMapFst(const Fst &fst, C *mapper) - : ImplToFst( - std::make_shared(fst, mapper, StateMapFstOptions())) {} - - // See Fst<>::Copy() for doc. - StateMapFst(const StateMapFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Get a copy of this StateMapFst. See Fst<>::Copy() for further doc. - StateMapFst *Copy(bool safe = false) const override { - return new StateMapFst(*this, safe); - } - - void InitStateIterator(StateIteratorData *data) const override { - GetImpl()->InitStateIterator(data); - } - - void InitArcIterator(StateId state, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(state, data); - } - - protected: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - private: - StateMapFst &operator=(const StateMapFst &) = delete; -}; - -// Specialization for StateMapFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename A::StateId; - - ArcIterator(const StateMapFst &fst, StateId state) - : CacheArcIterator>(fst.GetMutableImpl(), state) { - if (!fst.GetImpl()->HasArcs(state)) fst.GetMutableImpl()->Expand(state); - } -}; - -// Utility mappers. - -// Mapper that returns its input. -template -class IdentityStateMapper { - public: - using FromArc = Arc; - using ToArc = Arc; - - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit IdentityStateMapper(const Fst &fst) : fst_(fst) {} - - // Allows updating FST argument; pass only if changed. - IdentityStateMapper(const IdentityStateMapper &mapper, - const Fst *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_ = std::make_unique>>(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_t Properties(uint64_t props) const { return props; } - - private: - const Fst &fst_; - std::unique_ptr>> aiter_; -}; - -template -class ArcSumMapper { - public: - using FromArc = Arc; - using ToArc = Arc; - - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit ArcSumMapper(const Fst &fst) : fst_(fst), i_(0) {} - - // Allows updating FST argument; pass only if changed. - ArcSumMapper(const ArcSumMapper &mapper, const Fst *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> 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_t Properties(uint64_t 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 &fst_; - Compare comp_; - Equal equal_; - std::vector arcs_; - ssize_t i_; // Current arc position. - - ArcSumMapper &operator=(const ArcSumMapper &) = delete; -}; - -template -class ArcUniqueMapper { - public: - using FromArc = Arc; - using ToArc = Arc; - - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - explicit ArcUniqueMapper(const Fst &fst) : fst_(fst), i_(0) {} - - // Allows updating FST argument; pass only if changed. - ArcUniqueMapper(const ArcUniqueMapper &mapper, - const Fst *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> 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_t Properties(uint64_t 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 &fst_; - Compare comp_; - Equal equal_; - std::vector arcs_; - size_t i_; // Current arc position. - - ArcUniqueMapper &operator=(const ArcUniqueMapper &) = delete; -}; - -// Useful aliases when using StdArc. - -using StdArcSumMapper = ArcSumMapper; - -using StdArcUniqueMapper = ArcUniqueMapper; - -} // namespace fst - -#endif // FST_STATE_MAP_H_ diff --git a/contrib/fstlib/fst/state-reachable.h b/contrib/fstlib/fst/state-reachable.h deleted file mode 100644 index 33e1dc2..0000000 --- a/contrib/fstlib/fst/state-reachable.h +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Class to determine whether a given (final) state can be reached from some -// other given state. - -#ifndef FST_STATE_REACHABLE_H_ -#define FST_STATE_REACHABLE_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Computes the (final) states reachable from a given state in an FST. After -// this visitor has been called, a final state f can be reached from a state -// s iff (*isets)[s].Member(state2index[f]) is true, where (*isets[s]) is a -// set of half-open interval of final state indices and state2index[f] maps from -// a final state to its index. If state2index is empty, it is filled-in with -// suitable indices. If it is non-empty, those indices are used; in this case, -// the final states must have out-degree 0. -template > -class IntervalReachVisitor { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Index = I; - using ISet = S; - using Interval = typename ISet::Interval; - - IntervalReachVisitor(const Fst &fst, std::vector *isets, - std::vector *state2index) - : fst_(fst), - isets_(isets), - state2index_(state2index), - index_(state2index->empty() ? 1 : -1), - error_(false) { - isets_->clear(); - } - - void InitVisit(const Fst &) { error_ = false; } - - bool InitState(StateId s, StateId r) { - while (isets_->size() <= s) isets_->push_back(S()); - while (state2index_->size() <= s) state2index_->push_back(-1); - if (fst_.Final(s) != Weight::Zero()) { - // Create tree interval. - auto *intervals = (*isets_)[s].MutableIntervals(); - if (index_ < 0) { // Uses state2index_ map to set index. - if (fst_.NumArcs(s) > 0) { - FSTERROR() << "IntervalReachVisitor: state2index map must be empty " - << "for this FST"; - error_ = true; - return false; - } - const auto index = (*state2index_)[s]; - if (index < 0) { - FSTERROR() << "IntervalReachVisitor: state2index map incomplete"; - error_ = true; - return false; - } - intervals->push_back(Interval(index, index + 1)); - } else { // Use pre-order index. - intervals->push_back(Interval(index_, index_ + 1)); - (*state2index_)[s] = index_++; - } - } - return true; - } - - constexpr bool TreeArc(StateId, const Arc &) const { return true; } - - bool BackArc(StateId s, const Arc &arc) { - FSTERROR() << "IntervalReachVisitor: Cyclic input"; - error_ = true; - return false; - } - - bool ForwardOrCrossArc(StateId s, const Arc &arc) { - // Non-tree interval. - (*isets_)[s].Union((*isets_)[arc.nextstate]); - return true; - } - - void FinishState(StateId s, StateId p, const Arc *) { - if (index_ >= 0 && fst_.Final(s) != Weight::Zero()) { - auto *intervals = (*isets_)[s].MutableIntervals(); - (*intervals)[0].end = index_; // Updates tree interval end. - } - (*isets_)[s].Normalize(); - if (p != kNoStateId) { - (*isets_)[p].Union((*isets_)[s]); // Propagates intervals to parent. - } - } - - void FinishVisit() {} - - bool Error() const { return error_; } - - private: - const Fst &fst_; - std::vector *isets_; - std::vector *state2index_; - Index index_; - bool error_; -}; - -// Tests reachability of final states from a given state. To test for -// reachability from a state s, first do SetState(s). Then a final state f can -// be reached from state s of FST iff Reach(f) is true. The input can be cyclic, -// but no cycle may contain a final state. -template > -class StateReachable { - public: - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using Index = I; - using ISet = S; - using Interval = typename ISet::Interval; - - explicit StateReachable(const Fst &fst) : error_(false) { - if (fst.Properties(kAcyclic, true)) { - AcyclicStateReachable(fst); - } else { - CyclicStateReachable(fst); - } - } - - explicit StateReachable(const StateReachable &reachable) { - FSTERROR() << "Copy constructor for state reachable class " - << "not implemented."; - error_ = true; - } - - // Sets current state. - void SetState(StateId s) { s_ = s; } - - // Can reach this final state from current state? - bool Reach(StateId s) { - if (s >= state2index_.size()) return false; - const auto i = state2index_[s]; - if (i < 0) { - FSTERROR() << "StateReachable: State non-final: " << s; - error_ = true; - return false; - } - return isets_[s_].Member(i); - } - - // Access to the state-to-index mapping. Unassigned states have index -1. - std::vector &State2Index() { return state2index_; } - - // Access to the interval sets. These specify the reachability to the final - // states as intervals of the final state indices. - const std::vector &IntervalSets() { return isets_; } - - bool Error() const { return error_; } - - private: - void AcyclicStateReachable(const Fst &fst) { - IntervalReachVisitor reach_visitor(fst, &isets_, - &state2index_); - DfsVisit(fst, &reach_visitor); - if (reach_visitor.Error()) error_ = true; - } - - void CyclicStateReachable(const Fst &fst) { - // Finds state reachability on the acyclic condensation FST. - VectorFst cfst; - std::vector scc; - Condense(fst, &cfst, &scc); - StateReachable reachable(cfst); - if (reachable.Error()) { - error_ = true; - return; - } - // Gets the number of states per SCC. - std::vector nscc; - for (StateId s = 0; s < scc.size(); ++s) { - const auto c = scc[s]; - while (c >= nscc.size()) nscc.push_back(0); - ++nscc[c]; - } - // Constructs the interval sets and state index mapping for the original - // FST from the condensation FST. - state2index_.resize(scc.size(), -1); - isets_.resize(scc.size()); - for (StateId s = 0; s < scc.size(); ++s) { - const auto c = scc[s]; - isets_[s] = reachable.IntervalSets()[c]; - state2index_[s] = reachable.State2Index()[c]; - // Checks that each final state in an input FST is not contained in a - // cycle (i.e., not in a non-trivial SCC). - if (cfst.Final(c) != Weight::Zero() && nscc[c] > 1) { - FSTERROR() << "StateReachable: Final state contained in a cycle"; - error_ = true; - return; - } - } - } - - StateId s_; // Current state. - std::vector isets_; // Interval sets per state. - std::vector state2index_; // Finds index for a final state. - bool error_; - - StateReachable &operator=(const StateReachable &) = delete; -}; - -} // namespace fst - -#endif // FST_STATE_REACHABLE_H_ diff --git a/contrib/fstlib/fst/state-table.h b/contrib/fstlib/fst/state-table.h deleted file mode 100644 index 8cca8a3..0000000 --- a/contrib/fstlib/fst/state-table.h +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes for representing the mapping between state tuples and state IDs. - -#ifndef FST_STATE_TABLE_H_ -#define FST_STATE_TABLE_H_ - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// State tables determine the bijective mapping between state tuples (e.g., in -// composition, triples of two FST states and a composition filter state) and -// their corresponding state IDs. They are classes, templated on state tuples, -// with the following interface: -// -// template -// class StateTable { -// public: -// using StateTuple = T; -// -// // Required constructors. -// StateTable(); -// -// StateTable(const StateTable &); -// -// // Looks up state ID by tuple. If it doesn't exist, then add it. -// StateId FindState(const StateTuple &tuple); -// -// // Looks up state tuple by state ID. -// const StateTuple &Tuple(StateId s) const; -// -// // # of stored tuples. -// StateId Size() const; -// }; -// -// A state tuple has the form: -// -// template -// struct StateTuple { -// using StateId = S; -// -// // Required constructors. -// -// StateTuple(); -// -// StateTuple(const StateTuple &tuple); -// }; - -// An implementation using a hash map for the tuple to state ID mapping. The -// state tuple T must support operator==. -template -class HashStateTable : public HashBiTable { - public: - using StateTuple = T; - using StateId = typename StateTuple::StateId; - - using HashBiTable::FindId; - using HashBiTable::FindEntry; - using HashBiTable::Size; - - HashStateTable() : HashBiTable() {} - - explicit HashStateTable(size_t table_size) - : HashBiTable(table_size) {} - - StateId FindState(const StateTuple &tuple) { return FindId(tuple); } - - const StateTuple &Tuple(StateId s) const { return FindEntry(s); } -}; - -// An implementation using a hash map for the tuple to state ID mapping. The -// state tuple T must support operator==. -template -class CompactHashStateTable - : public CompactHashBiTable { - public: - using StateTuple = T; - using StateId = typename StateTuple::StateId; - - using CompactHashBiTable::FindId; - using CompactHashBiTable::FindEntry; - using CompactHashBiTable::Size; - - CompactHashStateTable() : CompactHashBiTable() {} - - explicit CompactHashStateTable(size_t table_size) - : CompactHashBiTable(table_size) {} - - StateId FindState(const StateTuple &tuple) { return FindId(tuple); } - - const StateTuple &Tuple(StateId s) const { return FindEntry(s); } -}; - -// An implementation using a vector for the tuple to state mapping. It is -// passed a fingerprint functor that should fingerprint tuples uniquely to an -// integer that can used as a vector index. Normally, VectorStateTable -// constructs the fingerprint functor. Alternately, the user can pass this -// object, in which case the table takes ownership. -template -class VectorStateTable : public VectorBiTable { - public: - using StateTuple = T; - using StateId = typename StateTuple::StateId; - - using VectorBiTable::FindId; - using VectorBiTable::FindEntry; - using VectorBiTable::Size; - using VectorBiTable::Fingerprint; - - explicit VectorStateTable(const FP &fingerprint = FP(), size_t table_size = 0) - : VectorBiTable(fingerprint, table_size) {} - - StateId FindState(const StateTuple &tuple) { return FindId(tuple); } - - const StateTuple &Tuple(StateId s) const { return FindEntry(s); } -}; - -// An implementation using a vector and a compact hash table. The selection -// functor returns true for tuples to be hashed in the vector. The fingerprint -// functor should fingerprint tuples uniquely to an integer that can be used as -// a vector index. A hash functor is used when hashing tuples into the compact -// hash table. -template -class VectorHashStateTable - : public VectorHashBiTable { - public: - using StateTuple = T; - using StateId = typename StateTuple::StateId; - - using VectorHashBiTable::FindId; - using VectorHashBiTable::FindEntry; - using VectorHashBiTable::Size; - using VectorHashBiTable::Selector; - using VectorHashBiTable::Fingerprint; - using VectorHashBiTable::HashFunction; - - VectorHashStateTable(const Select &select, const FP &fingerprint, - const H &hash, size_t vector_size = 0, - size_t tuple_size = 0) - : VectorHashBiTable( - select, fingerprint, hash, vector_size, tuple_size) {} - - StateId FindState(const StateTuple &tuple) { return FindId(tuple); } - - const StateTuple &Tuple(StateId s) const { return FindEntry(s); } -}; - -// An implementation using a hash map to map from tuples to state IDs. This -// version permits erasing of states. The state tuple's default constructor -// must produce a tuple that will never be seen and the table must suppor -// operator==. -template -class ErasableStateTable : public ErasableBiTable { - public: - using StateTuple = T; - using StateId = typename StateTuple::StateId; - - using ErasableBiTable::FindId; - using ErasableBiTable::FindEntry; - using ErasableBiTable::Size; - using ErasableBiTable::Erase; - - ErasableStateTable() : ErasableBiTable() {} - - StateId FindState(const StateTuple &tuple) { return FindId(tuple); } - - const StateTuple &Tuple(StateId s) const { return FindEntry(s); } -}; - -// The composition state table has the form: -// -// template -// class ComposeStateTable { -// public: -// using StateId = typename Arc::StateId; -// -// // Required constructors. -// -// ComposeStateTable(const Fst &fst1, const Fst &fst2); -// ComposeStateTable(const ComposeStateTable &table); -// -// // Looks up a state ID by tuple, adding it if doesn't exist. -// StateId FindState(const StateTuple &tuple); -// -// // Looks up a tuple by state ID. -// const ComposeStateTuple &Tuple(StateId s) const; -// -// // The number of stored tuples. -// StateId Size() const; -// -// // Return true if error was encountered. -// bool Error() const; -// }; -// -// The following interface is used to represent the composition state. -// -// template -// class CompositionStateTuple { -// public: -// using StateId = typename StateId; -// using FS = FilterState; -// -// // Required constructors. -// StateTuple(); -// StateTuple(StateId s1, StateId s2, const FilterState &fs); -// -// StateId StateId1() const; -// StateId StateId2() const; -// -// FilterState GetFilterState() const; -// -// std::pair StatePair() const; -// -// size_t Hash() const; -// -// friend bool operator==(const StateTuple& x, const StateTuple &y); -// } -// -template -class DefaultComposeStateTuple { - public: - using StateId = S; - using FilterState = FS; - - DefaultComposeStateTuple() - : state_pair_(kNoStateId, kNoStateId), fs_(FilterState::NoState()) {} - - DefaultComposeStateTuple(StateId s1, StateId s2, const FilterState &fs) - : state_pair_(s1, s2), fs_(fs) {} - - StateId StateId1() const { return state_pair_.first; } - - StateId StateId2() const { return state_pair_.second; } - - FilterState GetFilterState() const { return fs_; } - - const std::pair &StatePair() const { return state_pair_; } - - friend bool operator==(const DefaultComposeStateTuple &x, - const DefaultComposeStateTuple &y) { - return (&x == &y) || (x.state_pair_ == y.state_pair_ && x.fs_ == y.fs_); - } - - size_t Hash() const { - return static_cast(StateId1()) + - static_cast(StateId2()) * 7853u + - GetFilterState().Hash() * 7867u; - } - - private: - std::pair state_pair_; - FilterState fs_; // State of composition filter. -}; - -// Specialization for TrivialFilterState that does not explicitly store the -// filter state since it is always the unique non-blocking state. -template -class DefaultComposeStateTuple { - public: - using StateId = S; - using FilterState = TrivialFilterState; - - DefaultComposeStateTuple() : state_pair_(kNoStateId, kNoStateId) {} - - DefaultComposeStateTuple(StateId s1, StateId s2, const FilterState &) - : state_pair_(s1, s2) {} - - StateId StateId1() const { return state_pair_.first; } - - StateId StateId2() const { return state_pair_.second; } - - FilterState GetFilterState() const { return FilterState(true); } - - const std::pair &StatePair() const { return state_pair_; } - - friend bool operator==(const DefaultComposeStateTuple &x, - const DefaultComposeStateTuple &y) { - return (&x == &y) || (x.state_pair_ == y.state_pair_); - } - - size_t Hash() const { return StateId1() + StateId2() * size_t{7853}; } - - private: - std::pair state_pair_; -}; - -// Hashing of composition state tuples. -template -class ComposeHash { - public: - size_t operator()(const T &t) const { return t.Hash(); } -}; - -// A HashStateTable over composition tuples. -template , - typename StateTable = - CompactHashStateTable>> -class GenericComposeStateTable : public StateTable { - public: - using StateId = typename Arc::StateId; - - GenericComposeStateTable(const Fst &fst1, const Fst &fst2) {} - - GenericComposeStateTable(const Fst &fst1, const Fst &fst2, - size_t table_size) - : StateTable(table_size) {} - - constexpr bool Error() const { return false; } - - private: - GenericComposeStateTable &operator=(const GenericComposeStateTable &table) = - delete; -}; - -// Fingerprint for general composition tuples. -template -class ComposeFingerprint { - public: - using StateId = typename StateTuple::StateId; - - // Required but suboptimal constructor. - ComposeFingerprint() : mult1_(8192), mult2_(8192) { - LOG(WARNING) << "TupleFingerprint: # of FST states should be provided."; - } - - // Constructor is provided the sizes of the input FSTs. - ComposeFingerprint(StateId nstates1, StateId nstates2) - : mult1_(nstates1), mult2_(nstates1 * nstates2) {} - - size_t operator()(const StateTuple &tuple) const { - return tuple.StateId1() + tuple.StateId2() * mult1_ + - tuple.GetFilterState().Hash() * mult2_; - } - - private: - const ssize_t mult1_; - const ssize_t mult2_; -}; - -// Useful when the first composition state determines the tuple. -template -class ComposeState1Fingerprint { - public: - size_t operator()(const StateTuple &tuple) { return tuple.StateId1(); } -}; - -// Useful when the second composition state determines the tuple. -template -class ComposeState2Fingerprint { - public: - size_t operator()(const StateTuple &tuple) { return tuple.StateId2(); } -}; - -// A VectorStateTable over composition tuples. This can be used when the -// product of number of states in FST1 and FST2 (and the composition filter -// state hash) is manageable. If the FSTs are not expanded FSTs, they will -// first have their states counted. -template -class ProductComposeStateTable - : public VectorStateTable> { - public: - using StateId = typename Arc::StateId; - using StateTable = - VectorStateTable>; - - ProductComposeStateTable(const Fst &fst1, const Fst &fst2, - size_t table_size = 0) - : StateTable(ComposeFingerprint(CountStates(fst1), - CountStates(fst2)), - table_size) {} - - ProductComposeStateTable( - const ProductComposeStateTable &table) - : StateTable(ComposeFingerprint(table.Fingerprint())) {} - - constexpr bool Error() const { return false; } - - private: - ProductComposeStateTable &operator=(const ProductComposeStateTable &table) = - delete; -}; - -// A vector-backed table over composition tuples which can be used when the -// first FST is a string (i.e., satisfies kString property) and the second is -// deterministic and epsilon-free. It should be used with a composition filter -// that creates at most one filter state per tuple under these conditions (e.g., -// SequenceComposeFilter or MatchComposeFilter). -template -class StringDetComposeStateTable - : public VectorStateTable> { - public: - using StateId = typename Arc::StateId; - using StateTable = - VectorStateTable>; - - StringDetComposeStateTable(const Fst &fst1, const Fst &fst2) - : error_(false) { - static constexpr auto props2 = kIDeterministic | kNoIEpsilons; - if (fst1.Properties(kString, true) != kString) { - FSTERROR() << "StringDetComposeStateTable: 1st FST is not a string"; - error_ = true; - } else if (fst2.Properties(props2, true) != props2) { - FSTERROR() << "StringDetComposeStateTable: 2nd FST is not deterministic " - "and epsilon-free"; - error_ = true; - } - } - - StringDetComposeStateTable( - const StringDetComposeStateTable &table) - : StateTable(table), error_(table.error_) {} - - bool Error() const { return error_; } - - private: - bool error_; - - StringDetComposeStateTable &operator=(const StringDetComposeStateTable &) = - delete; -}; - -// A vector-backed table over composition tuples which can be used when the -// first FST is deterministic and epsilon-free and the second is a string (i.e., -// satisfies kString). It should be used with a composition filter that creates -// at most one filter state per tuple under these conditions (e.g., -// SequenceComposeFilter or MatchComposeFilter). -template -class DetStringComposeStateTable - : public VectorStateTable> { - public: - using StateId = typename Arc::StateId; - using StateTable = - VectorStateTable>; - - DetStringComposeStateTable(const Fst &fst1, const Fst &fst2) - : error_(false) { - static constexpr auto props = kODeterministic | kNoOEpsilons; - if (fst1.Properties(props, true) != props) { - FSTERROR() << "StringDetComposeStateTable: 1st FST is not " - << "input-deterministic and epsilon-free"; - error_ = true; - } else if (fst2.Properties(kString, true) != kString) { - FSTERROR() << "DetStringComposeStateTable: 2nd FST is not a string"; - error_ = true; - } - } - - DetStringComposeStateTable( - const DetStringComposeStateTable &table) - : StateTable(table), error_(table.error_) {} - - bool Error() const { return error_; } - - private: - bool error_; - - DetStringComposeStateTable &operator=(const DetStringComposeStateTable &) = - delete; -}; - -// An erasable table over composition tuples. The Erase(StateId) method can be -// called if the user either is sure that composition will never return to that -// tuple or doesn't care that if it does, it is assigned a new state ID. -template -class ErasableComposeStateTable - : public ErasableStateTable> { - public: - ErasableComposeStateTable(const Fst &fst1, const Fst &fst2) {} - - constexpr bool Error() const { return false; } - - private: - ErasableComposeStateTable &operator=(const ErasableComposeStateTable &table) = - delete; -}; - -} // namespace fst - -#endif // FST_STATE_TABLE_H_ diff --git a/contrib/fstlib/fst/statesort.h b/contrib/fstlib/fst/statesort.h deleted file mode 100644 index 4ed79c4..0000000 --- a/contrib/fstlib/fst/statesort.h +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function to sort states of an FST. - -#ifndef FST_STATESORT_H_ -#define FST_STATESORT_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -// Sorts the input states of an FST. order[i] gives the state ID after -// sorting that corresponds to the state ID i before sorting; it must -// therefore be a permutation of the input FST's states ID sequence. -template -void StateSort(MutableFst *fst, - const std::vector &order) { - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - if (order.size() != fst->NumStates()) { - FSTERROR() << "StateSort: Bad order vector size: " << order.size(); - fst->SetProperties(kError, kError); - return; - } - if (fst->Start() == kNoStateId) return; - const auto props = fst->Properties(kStateSortProperties, false); - std::vector done(order.size(), false); - std::vector arcsa; - std::vector arcsb; - fst->SetStart(order[fst->Start()]); - for (StateIterator> siter(*fst); !siter.Done(); - siter.Next()) { - auto s1 = siter.Value(); - StateId s2; - if (done[s1]) continue; - auto final1 = fst->Final(s1); - auto final2 = Weight::Zero(); - arcsa.clear(); - for (ArcIterator> aiter(*fst, s1); !aiter.Done(); - aiter.Next()) { - arcsa.push_back(aiter.Value()); - } - for (; !done[s1]; s1 = s2, final1 = final2, std::swap(arcsa, arcsb)) { - s2 = order[s1]; - if (!done[s2]) { - final2 = fst->Final(s2); - arcsb.clear(); - for (ArcIterator> aiter(*fst, s2); !aiter.Done(); - aiter.Next()) { - arcsb.push_back(aiter.Value()); - } - } - fst->SetFinal(s2, final1); - fst->DeleteArcs(s2); - for (auto arc : arcsa) { // NOLINT(performance-for-range-copy) - arc.nextstate = order[arc.nextstate]; - fst->AddArc(s2, arc); - } - done[s1] = true; - } - } - fst->SetProperties(props, kFstProperties); -} - -} // namespace fst - -#endif // FST_STATESORT_H_ diff --git a/contrib/fstlib/fst/string-weight.h b/contrib/fstlib/fst/string-weight.h deleted file mode 100644 index fce7e17..0000000 --- a/contrib/fstlib/fst/string-weight.h +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// String weight set and associated semiring operation definitions. - -#ifndef FST_STRING_WEIGHT_H_ -#define FST_STRING_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace fst { - -inline constexpr int kStringInfinity = -1; // Label for the infinite string. -inline constexpr int kStringBad = -2; // Label for a non-string. -inline constexpr char kStringSeparator = '_'; // Label separator in strings. - -// Determines whether to use left or right string semiring. Includes a -// 'restricted' version that signals an error if proper prefixes/suffixes -// would otherwise be returned by Plus, useful with various -// algorithms that require functional transducer input with the -// string semirings. -enum StringType { STRING_LEFT = 0, STRING_RIGHT = 1, STRING_RESTRICT = 2 }; - -constexpr StringType ReverseStringType(StringType s) { - return s == STRING_LEFT ? STRING_RIGHT - : (s == STRING_RIGHT ? STRING_LEFT : STRING_RESTRICT); -} - -template -class StringWeightIterator; -template -class StringWeightReverseIterator; - -// String semiring: (longest_common_prefix/suffix, ., Infinity, Epsilon) -template -class StringWeight { - public: - using Label = L; - using ReverseWeight = StringWeight; - using Iterator = StringWeightIterator; - using ReverseIterator = StringWeightReverseIterator; - - friend class StringWeightIterator; - friend class StringWeightReverseIterator; - - StringWeight() = default; - - template - StringWeight(const Iterator begin, const Iterator end) { - for (auto iter = begin; iter != end; ++iter) PushBack(*iter); - } - - explicit StringWeight(Label label) { PushBack(label); } - - static const StringWeight &Zero() { - static const auto *const zero = new StringWeight(Label(kStringInfinity)); - return *zero; - } - - static const StringWeight &One() { - static const auto *const one = new StringWeight(); - return *one; - } - - static const StringWeight &NoWeight() { - static const auto *const no_weight = new StringWeight(Label(kStringBad)); - return *no_weight; - } - - static const std::string &Type() { - static const std::string *const type = new std::string( - S == STRING_LEFT - ? "left_string" - : (S == STRING_RIGHT ? "right_string" : "restricted_string")); - return *type; - } - - bool Member() const; - - std::istream &Read(std::istream &strm); - - std::ostream &Write(std::ostream &strm) const; - - size_t Hash() const; - - StringWeight Quantize(float delta = kDelta) const { return *this; } - - ReverseWeight Reverse() const; - - static constexpr uint64_t Properties() { - return kIdempotent | - (S == STRING_LEFT ? kLeftSemiring - : (S == STRING_RIGHT - ? kRightSemiring - : /* S == STRING_RESTRICT */ kLeftSemiring | - kRightSemiring)); - } - - // These operations combined with the StringWeightIterator and - // StringWeightReverseIterator provide the access and mutation of the string - // internal elements. - - // Clear existing StringWeight. - void Clear() { - first_ = 0; - rest_.clear(); - } - - size_t Size() const { return first_ ? rest_.size() + 1 : 0; } - - void PushFront(Label label) { - if (first_) rest_.push_front(first_); - first_ = label; - } - - void PushBack(Label label) { - if (!first_) { - first_ = label; - } else { - rest_.push_back(label); - } - } - - private: - Label first_ = 0; // First label in string (0 if empty). - std::list; - - friend class ArcIterator>; - friend class StateIterator>; - - explicit SynchronizeFst(const Fst &fst, const SynchronizeFstOptions &opts = - SynchronizeFstOptions()) - : ImplToFst(std::make_shared(fst, opts)) {} - - // See Fst<>::Copy() for doc. - SynchronizeFst(const SynchronizeFst &fst, bool safe = false) - : ImplToFst(fst, safe) {} - - // Gets a copy of this SynchronizeFst. See Fst<>::Copy() for further doc. - SynchronizeFst *Copy(bool safe = false) const override { - return new SynchronizeFst(*this, safe); - } - - inline void InitStateIterator(StateIteratorData *data) const override; - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetMutableImpl()->InitArcIterator(s, data); - } - - private: - using ImplToFst::GetImpl; - using ImplToFst::GetMutableImpl; - - SynchronizeFst &operator=(const SynchronizeFst &) = delete; -}; - -// Specialization for SynchronizeFst. -template -class StateIterator> - : public CacheStateIterator> { - public: - explicit StateIterator(const SynchronizeFst &fst) - : CacheStateIterator>(fst, fst.GetMutableImpl()) {} -}; - -// Specialization for SynchronizeFst. -template -class ArcIterator> - : public CacheArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const SynchronizeFst &fst, StateId s) - : CacheArcIterator>(fst.GetMutableImpl(), s) { - if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); - } -}; - -template -inline void SynchronizeFst::InitStateIterator( - StateIteratorData *data) const { - data->base = std::make_unique>>(*this); -} - -// Synchronizes a transducer. This version writes the synchronized result to a -// MutableFst. The result will be an equivalent FST that has the property that -// during the traversal of a path, the delay is either zero or strictly -// increasing, where the delay is the difference between the number of -// non-epsilon output labels and input labels along the path. -// -// For the algorithm to terminate, the input transducer must have bounded -// delay, i.e., the delay of every cycle must be zero. -// -// Complexity: -// -// - A has bounded delay: exponential. -// - A does not have bounded delay: does not terminate. -// -// For more information, see: -// -// Mohri, M. 2003. Edit-distance of weighted automata: General definitions and -// algorithms. International Journal of Computer Science 14(6): 957-982. -template -void Synchronize(const Fst &ifst, MutableFst *ofst) { - // Caches only the last state for fastest copy. - const SynchronizeFstOptions opts(FST_FLAGS_fst_default_cache_gc, - 0); - *ofst = SynchronizeFst(ifst, opts); -} - -} // namespace fst - -#endif // FST_SYNCHRONIZE_H_ diff --git a/contrib/fstlib/fst/test-properties.h b/contrib/fstlib/fst/test-properties.h deleted file mode 100644 index 8e651ee..0000000 --- a/contrib/fstlib/fst/test-properties.h +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions to manipulate and test property bits. - -#ifndef FST_TEST_PROPERTIES_H_ -#define FST_TEST_PROPERTIES_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -DECLARE_bool(fst_verify_properties); - -namespace fst { -namespace internal { - -// Computes FST property values defined in properties.h. The value of each -// property indicated in the mask will be determined and returned (these will -// never be unknown here). In the course of determining the properties -// specifically requested in the mask, certain other properties may be -// determined (those with little additional expense) and their values will be -// returned as well. The complete set of known properties (whether true or -// false) determined by this operation will be assigned to the value pointed -// to by KNOWN. 'mask & required_mask' is used to determine whether the stored -// properties can be used. This routine is seldom called directly; instead it is -// used to implement fst.Properties(mask, /*test=*/true). -template -uint64_t ComputeProperties(const Fst &fst, uint64_t mask, - uint64_t *known) { - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - const auto fst_props = fst.Properties(kFstProperties, false); // FST-stored. - // Computes (trinary) properties explicitly. - // Initialize with binary properties (already known). - uint64_t comp_props = fst_props & kBinaryProperties; - // Computes these trinary properties with a DFS. We compute only those that - // need a DFS here, since we otherwise would like to avoid a DFS since its - // stack could grow large. - constexpr uint64_t kDfsProps = - kCyclic | kAcyclic | kInitialCyclic | kInitialAcyclic | kAccessible | - kNotAccessible | kCoAccessible | kNotCoAccessible; - std::vector scc; - if (mask & (kDfsProps | kWeightedCycles | kUnweightedCycles)) { - SccVisitor scc_visitor(&scc, nullptr, nullptr, &comp_props); - DfsVisit(fst, &scc_visitor); - } - // Computes any remaining trinary properties via a state and arcs iterations - if (mask & ~(kBinaryProperties | kDfsProps)) { - comp_props |= kAcceptor | kNoEpsilons | kNoIEpsilons | kNoOEpsilons | - kILabelSorted | kOLabelSorted | kUnweighted | kTopSorted | - kString; - if (mask & (kIDeterministic | kNonIDeterministic)) { - comp_props |= kIDeterministic; - } - if (mask & (kODeterministic | kNonODeterministic)) { - comp_props |= kODeterministic; - } - if (mask & (kDfsProps | kWeightedCycles | kUnweightedCycles)) { - comp_props |= kUnweightedCycles; - } - std::optional> ilabels; - std::optional> olabels; - StateId nfinal = 0; - for (StateIterator> siter(fst); !siter.Done(); siter.Next()) { - StateId s = siter.Value(); - Arc prev_arc; - // Creates these only if we need to. - if (mask & (kIDeterministic | kNonIDeterministic)) { - ilabels.emplace(); - } - if (mask & (kODeterministic | kNonODeterministic)) { - olabels.emplace(); - } - bool first_arc = true; - for (ArcIterator> aiter(fst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - if (ilabels && ilabels->find(arc.ilabel) != ilabels->end()) { - comp_props |= kNonIDeterministic; - comp_props &= ~kIDeterministic; - } - if (olabels && olabels->find(arc.olabel) != olabels->end()) { - comp_props |= kNonODeterministic; - comp_props &= ~kODeterministic; - } - if (arc.ilabel != arc.olabel) { - comp_props |= kNotAcceptor; - comp_props &= ~kAcceptor; - } - if (arc.ilabel == 0 && arc.olabel == 0) { - comp_props |= kEpsilons; - comp_props &= ~kNoEpsilons; - } - if (arc.ilabel == 0) { - comp_props |= kIEpsilons; - comp_props &= ~kNoIEpsilons; - } - if (arc.olabel == 0) { - comp_props |= kOEpsilons; - comp_props &= ~kNoOEpsilons; - } - if (!first_arc) { - if (arc.ilabel < prev_arc.ilabel) { - comp_props |= kNotILabelSorted; - comp_props &= ~kILabelSorted; - } - if (arc.olabel < prev_arc.olabel) { - comp_props |= kNotOLabelSorted; - comp_props &= ~kOLabelSorted; - } - } - if (arc.weight != Weight::One() && arc.weight != Weight::Zero()) { - comp_props |= kWeighted; - comp_props &= ~kUnweighted; - if ((comp_props & kUnweightedCycles) && - scc[s] == scc[arc.nextstate]) { - comp_props |= kWeightedCycles; - comp_props &= ~kUnweightedCycles; - } - } - if (arc.nextstate <= s) { - comp_props |= kNotTopSorted; - comp_props &= ~kTopSorted; - } - if (arc.nextstate != s + 1) { - comp_props |= kNotString; - comp_props &= ~kString; - } - prev_arc = arc; - first_arc = false; - if (ilabels) ilabels->insert(arc.ilabel); - if (olabels) olabels->insert(arc.olabel); - } - - if (nfinal > 0) { // Final state not last. - comp_props |= kNotString; - comp_props &= ~kString; - } - const auto final_weight = fst.Final(s); - if (final_weight != Weight::Zero()) { // Final state. - if (final_weight != Weight::One()) { - comp_props |= kWeighted; - comp_props &= ~kUnweighted; - } - ++nfinal; - } else { // Non-final state. - if (fst.NumArcs(s) != 1) { - comp_props |= kNotString; - comp_props &= ~kString; - } - } - } - if (fst.Start() != kNoStateId && fst.Start() != 0) { - comp_props |= kNotString; - comp_props &= ~kString; - } - } - if (known) *known = KnownProperties(comp_props); - return comp_props; -} - -// Similar to ComputeProperties, but uses the properties already stored -// in the FST when possible. -template -uint64_t ComputeOrUseStoredProperties(const Fst &fst, uint64_t mask, - uint64_t *known) { - // Check stored FST properties first. - const auto fst_props = fst.Properties(kFstProperties, /*test=*/false); - const auto known_props = KnownProperties(fst_props); - // If FST contains required info, return it. - if ((known_props & mask) == mask) { - if (known) *known = known_props; - return fst_props; - } - - return ComputeProperties(fst, mask, known); -} - -// This is a wrapper around ComputeProperties that will cause a fatal error if -// the stored properties and the computed properties are incompatible when -// FST_FLAGS_fst_verify_properties is true. This routine is seldom called directly; -// instead it is used to implement fst.Properties(mask, /*test=*/true). -template -uint64_t TestProperties(const Fst &fst, uint64_t mask, uint64_t *known) { - if (FST_FLAGS_fst_verify_properties) { - const auto stored_props = fst.Properties(kFstProperties, false); - const auto computed_props = ComputeProperties(fst, mask, known); - if (!CompatProperties(stored_props, computed_props)) { - FSTERROR() << "TestProperties: stored FST properties incorrect" - << " (stored: props1, computed: props2)"; - } - return computed_props; - } else { - return ComputeOrUseStoredProperties(fst, mask, known); - } -} - -// If all the properties of 'fst' corresponding to 'check_mask' are known, -// returns the stored properties. Otherwise, the properties corresponding to -// both 'check_mask' and 'test_mask' are computed. This is used to check for -// newly-added properties that might not be set in old binary files. -template -uint64_t CheckProperties(const Fst &fst, uint64_t check_mask, - uint64_t test_mask) { - auto props = fst.Properties(kFstProperties, false); - if (FST_FLAGS_fst_verify_properties) { - props = TestProperties(fst, check_mask | test_mask, /*known=*/nullptr); - } else if ((KnownProperties(props) & check_mask) != check_mask) { - props = ComputeProperties(fst, check_mask | test_mask, /*known=*/nullptr); - } - return props & (check_mask | test_mask); -} - -} // namespace internal -} // namespace fst - -#endif // FST_TEST_PROPERTIES_H_ diff --git a/contrib/fstlib/fst/topsort.h b/contrib/fstlib/fst/topsort.h deleted file mode 100644 index f3a8f8c..0000000 --- a/contrib/fstlib/fst/topsort.h +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Topological sort of FSTs. - -#ifndef FST_TOPSORT_H_ -#define FST_TOPSORT_H_ - -#include - -#include -#include -#include -#include -#include - -namespace fst { - -// DFS visitor class to return topological ordering. -template -class TopOrderVisitor { - public: - using StateId = typename Arc::StateId; - - // If acyclic, order[i] gives the topological position of StateId i; - // otherwise it is unchanged. acyclic_ will be true iff the FST has no - // cycles. The caller retains ownership of the state order vector. - TopOrderVisitor(std::vector *order, bool *acyclic) - : order_(order), acyclic_(acyclic) {} - - void InitVisit(const Fst &fst) { - finish_.clear(); - *acyclic_ = true; - } - - constexpr bool InitState(StateId, StateId) const { return true; } - - constexpr bool TreeArc(StateId, const Arc &) const { return true; } - - bool BackArc(StateId, const Arc &) { return (*acyclic_ = false); } - - constexpr bool ForwardOrCrossArc(StateId, const Arc &) const { return true; } - - void FinishState(StateId s, StateId, const Arc *) { finish_.push_back(s); } - - void FinishVisit() { - if (*acyclic_) { - order_->clear(); - for (StateId s = 0; s < finish_.size(); ++s) { - order_->push_back(kNoStateId); - } - for (StateId s = 0; s < finish_.size(); ++s) { - (*order_)[finish_[finish_.size() - s - 1]] = s; - } - } - } - - private: - std::vector *order_; - bool *acyclic_; - // States in finish-time order. - std::vector finish_; -}; - -// Topologically sorts its input if acyclic, modifying it. Otherwise, the input -// is unchanged. When sorted, all transitions are from lower to higher state -// IDs. -// -// Complexity: -// -// Time: O(V + E) -// Space: O(V + E) -// -// where V is the number of states and E is the number of arcs. -template -bool TopSort(MutableFst *fst) { - std::vector order; - bool acyclic; - TopOrderVisitor top_order_visitor(&order, &acyclic); - DfsVisit(*fst, &top_order_visitor); - if (acyclic) { - StateSort(fst, order); - fst->SetProperties(kAcyclic | kInitialAcyclic | kTopSorted, - kAcyclic | kInitialAcyclic | kTopSorted); - } else { - fst->SetProperties(kCyclic | kNotTopSorted, kCyclic | kNotTopSorted); - } - return acyclic; -} - -} // namespace fst - -#endif // FST_TOPSORT_H_ diff --git a/contrib/fstlib/fst/tuple-weight.h b/contrib/fstlib/fst/tuple-weight.h deleted file mode 100644 index ace0c51..0000000 --- a/contrib/fstlib/fst/tuple-weight.h +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Tuple weight set operation definitions. - -#ifndef FST_TUPLE_WEIGHT_H_ -#define FST_TUPLE_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace fst { - -// n-tuple weight, element of the n-th Cartesian power of W. -template -class TupleWeight { - public: - using ReverseWeight = TupleWeight; - - using Weight = W; - using Index = size_t; - - template - TupleWeight(Iterator begin, Iterator end) { - std::copy(begin, end, values_.begin()); - } - - explicit TupleWeight(const W &weight = W::Zero()) { values_.fill(weight); } - - // Initialize component `index` to `weight`; initialize all other components - // to `default_weight` - TupleWeight(Index index, const W &weight, const W &default_weight) - : TupleWeight(default_weight) { - values_[index] = weight; - } - - static const TupleWeight &Zero() { - static const TupleWeight zero(W::Zero()); - return zero; - } - - static const TupleWeight &One() { - static const TupleWeight one(W::One()); - return one; - } - - static const TupleWeight &NoWeight() { - static const TupleWeight no_weight(W::NoWeight()); - return no_weight; - } - - constexpr static size_t Length() { return n; } - - std::istream &Read(std::istream &istrm) { - for (size_t i = 0; i < n; ++i) values_[i].Read(istrm); - return istrm; - } - - std::ostream &Write(std::ostream &ostrm) const { - for (size_t i = 0; i < n; ++i) values_[i].Write(ostrm); - return ostrm; - } - - bool Member() const { - return std::all_of(values_.begin(), values_.end(), std::mem_fn(&W::Member)); - } - - size_t Hash() const { - uint64_t hash = 0; - for (size_t i = 0; i < n; ++i) hash = 5 * hash + values_[i].Hash(); - return size_t(hash); - } - - TupleWeight Quantize(float delta = kDelta) const { - TupleWeight weight; - for (size_t i = 0; i < n; ++i) { - weight.values_[i] = values_[i].Quantize(delta); - } - return weight; - } - - ReverseWeight Reverse() const { - TupleWeight w; - for (size_t i = 0; i < n; ++i) w.values_[i] = values_[i].Reverse(); - return w; - } - - const W &Value(size_t i) const { return values_[i]; } - - void SetValue(size_t i, const W &w) { values_[i] = w; } - - private: - std::array values_; -}; - -template -inline bool operator==(const TupleWeight &w1, - const TupleWeight &w2) { - for (size_t i = 0; i < n; ++i) { - if (w1.Value(i) != w2.Value(i)) return false; - } - return true; -} - -template -inline bool operator!=(const TupleWeight &w1, - const TupleWeight &w2) { - for (size_t i = 0; i < n; ++i) { - if (w1.Value(i) != w2.Value(i)) return true; - } - return false; -} - -template -inline bool ApproxEqual(const TupleWeight &w1, - const TupleWeight &w2, float delta = kDelta) { - for (size_t i = 0; i < n; ++i) { - if (!ApproxEqual(w1.Value(i), w2.Value(i), delta)) return false; - } - return true; -} - -template -inline std::ostream &operator<<(std::ostream &strm, - const TupleWeight &w) { - CompositeWeightWriter writer(strm); - writer.WriteBegin(); - for (size_t i = 0; i < n; ++i) writer.WriteElement(w.Value(i)); - writer.WriteEnd(); - return strm; -} - -template -inline std::istream &operator>>(std::istream &strm, TupleWeight &w) { - CompositeWeightReader reader(strm); - reader.ReadBegin(); - W v; - // Reads first n-1 elements. - static_assert(n > 0, "Size must be positive."); - for (size_t i = 0; i < n - 1; ++i) { - reader.ReadElement(&v); - w.SetValue(i, v); - } - // Reads n-th element. - reader.ReadElement(&v, true); - w.SetValue(n - 1, v); - reader.ReadEnd(); - return strm; -} - -} // namespace fst - -#endif // FST_TUPLE_WEIGHT_H_ diff --git a/contrib/fstlib/fst/union-find.h b/contrib/fstlib/fst/union-find.h deleted file mode 100644 index 062ccaa..0000000 --- a/contrib/fstlib/fst/union-find.h +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Union-find algorithm for dense sets of non-negative integers, implemented -// using disjoint tree forests with rank heuristics and path compression. - -#ifndef FST_UNION_FIND_H_ -#define FST_UNION_FIND_H_ - -#include - -namespace fst { - -// Union-Find algorithm for dense sets of non-negative integers. -template -class UnionFind { - public: - // Creates a disjoint set forest for the range [0; max); 'fail' is a value - // indicating that an element hasn't been initialized using MakeSet(...). - // The upper bound of the range can be reset (increased) using MakeSet(...). - UnionFind(T max, T fail) : parent_(max, fail), rank_(max), fail_(fail) {} - - // Finds the representative of the set 'item' belongs to, performing path - // compression if necessary. - T FindSet(T item) { - if (item >= parent_.size() || item == fail_ || parent_[item] == fail_) { - return fail_; - } - T root = item; - while (root != parent_[root]) { - root = parent_[root]; - } - while (item != parent_[item]) { - T parent = parent_[item]; - parent_[item] = root; - item = parent; - } - return root; - } - - // Creates the (destructive) union of the sets x and y belong to. - void Union(T x, T y) { Link(FindSet(x), FindSet(y)); } - - // Initialization of an element: creates a singleton set containing 'item'. - // The range [0; max) is reset if item >= max. - T MakeSet(T item) { - if (item >= parent_.size()) { - // New value in parent_ should be initialized to fail_. - const auto nitem = item > 0 ? 2 * item : 2; - parent_.resize(nitem, fail_); - rank_.resize(nitem); - } - parent_[item] = item; - return item; - } - - // Initialization of all elements starting from 0 to max - 1 to distinct sets. - void MakeAllSet(T max) { - parent_.resize(max); - for (T item = 0; item < max; ++item) parent_[item] = item; - } - - // For testing only. - const T &Parent(const T &x) const { return parent_[x]; } - - private: - // Links trees rooted in 'x' and 'y'. - void Link(T x, T y) { - if (x == y) return; - if (rank_[x] > rank_[y]) { - parent_[y] = x; - } else { - parent_[x] = y; - if (rank_[x] == rank_[y]) { - ++rank_[y]; - } - } - } - - UnionFind(const UnionFind &) = delete; - - UnionFind &operator=(const UnionFind &) = delete; - - std::vector parent_; // Parent nodes. - std::vector rank_; // Rank of an element = min. depth in tree. - T fail_; // Value indicating lookup failure. -}; - -} // namespace fst - -#endif // FST_UNION_FIND_H_ diff --git a/contrib/fstlib/fst/union-weight.h b/contrib/fstlib/fst/union-weight.h deleted file mode 100644 index 04e0722..0000000 --- a/contrib/fstlib/fst/union-weight.h +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Union weight set and associated semiring operation definitions. -// -// TODO(riley): add in normalizer functor. - -#ifndef FST_UNION_WEIGHT_H_ -#define FST_UNION_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace fst { - -// Example UnionWeightOptions for UnionWeight template below. The Merge -// operation is used to collapse elements of the set and the Compare function -// to efficiently implement the merge. In the simplest case, merge would just -// apply with equality of set elements so the result is a set (and not a -// multiset). More generally, this can be used to maintain the multiplicity or -// other such weight associated with the set elements (cf. Gallic weights). - -// template -// struct UnionWeightOptions { -// // Comparison function C is a total order on W that is monotonic w.r.t. to -// // Times: for all a, b,c != Zero(): C(a, b) => C(ca, cb) and is -// // anti-monotonic w.r.rt to Divide: C(a, b) => C(c/b, c/a). -// // -// // For all a, b: only one of C(a, b), C(b, a) or a ~ b must true where -// // ~ is an equivalence relation on W. Also we require a ~ b iff -// // a.Reverse() ~ b.Reverse(). -// using Compare = NaturalLess; -// -// // How to combine two weights if a ~ b as above. For all a, b: a ~ b => -// // merge(a, b) ~ a, Merge must define a semiring endomorphism from the -// // unmerged weight sets to the merged weight sets. -// struct Merge { -// W operator()(const W &w1, const W &w2) const { return w1; } -// }; -// -// // For ReverseWeight. -// using ReverseOptions = UnionWeightOptions; -// }; - -template -class UnionWeight; -template -class UnionWeightIterator; -template -class UnionWeightReverseIterator; - -template -bool operator==(const UnionWeight &, const UnionWeight &); - -// Semiring that uses Times() and One() from W and union and the empty set -// for Plus() and Zero(), respectively. Template argument O specifies the union -// weight options as above. -template -class UnionWeight { - public: - using Weight = W; - using Compare = typename O::Compare; - using Merge = typename O::Merge; - - using ReverseWeight = - UnionWeight; - - friend class UnionWeightIterator; - friend class UnionWeightReverseIterator; - - // Sets represented as first_ weight + rest_ weights. Uses first_ as - // NoWeight() to indicate the union weight Zero() as the empty set. Uses - // rest_ containing NoWeight() to indicate the union weight NoWeight(). - UnionWeight() : first_(W::NoWeight()) {} - - explicit UnionWeight(W weight) : first_(weight) { - if (!weight.Member()) rest_.push_back(W::NoWeight()); - } - - static const UnionWeight &Zero() { - static const auto *const zero = new UnionWeight; - return *zero; - } - - static const UnionWeight &One() { - static const auto *const one = new UnionWeight(W::One()); - return *one; - } - - static const UnionWeight &NoWeight() { - static const auto *const no_weight = - new UnionWeight(W::Zero(), W::NoWeight()); - return *no_weight; - } - - static const std::string &Type() { - static const std::string *const type = - new std::string(W::Type() + "_union"); - return *type; - } - - static constexpr uint64_t Properties() { - return W::Properties() & - (kLeftSemiring | kRightSemiring | kCommutative | kIdempotent); - } - - bool Member() const; - - std::istream &Read(std::istream &strm); - - std::ostream &Write(std::ostream &strm) const; - - size_t Hash() const; - - UnionWeight Quantize(float delta = kDelta) const; - - ReverseWeight Reverse() const; - - // These operations combined with the UnionWeightIterator and - // UnionWeightReverseIterator provide the access and mutation of the union - // weight internal elements. - - // Common initializer among constructors; clears existing UnionWeight. - void Clear() { - first_ = W::NoWeight(); - rest_.clear(); - } - - size_t Size() const { return first_.Member() ? rest_.size() + 1 : 0; } - - const W &Back() const { return rest_.empty() ? first_ : rest_.back(); } - - // When srt is true, assumes elements added sorted w.r.t Compare and merging - // of weights performed as needed. Otherwise, just ensures first_ is the - // least element wrt Compare. - void PushBack(W weight, bool srt); - - // Sorts the elements of the set. Assumes that first_, if present, is the - // least element. - void Sort() { rest_.sort(comp_); } - - private: - W &Back() { - if (rest_.empty()) { - return first_; - } else { - return rest_.back(); - } - } - - UnionWeight(W w1, W w2) : first_(std::move(w1)), rest_(1, std::move(w2)) {} - - W first_; // First weight in set. - std::list rest_; // Remaining weights in set. - Compare comp_; - Merge merge_; -}; - -template -void UnionWeight::PushBack(W weight, bool srt) { - if (!weight.Member()) { - rest_.push_back(std::move(weight)); - } else if (!first_.Member()) { - first_ = std::move(weight); - } else if (srt) { - auto &back = Back(); - if (comp_(back, weight)) { - rest_.push_back(std::move(weight)); - } else { - back = merge_(back, std::move(weight)); - } - } else { - if (comp_(first_, weight)) { - rest_.push_back(std::move(weight)); - } else { - rest_.push_back(first_); - first_ = std::move(weight); - } - } -} - -// Traverses union weight in the forward direction. -template -class UnionWeightIterator { - public: - explicit UnionWeightIterator(const UnionWeight &weight) - : first_(weight.first_), - rest_(weight.rest_), - init_(true), - it_(rest_.begin()) {} - - bool Done() const { return init_ ? !first_.Member() : it_ == rest_.end(); } - - const W &Value() const { return init_ ? first_ : *it_; } - - void Next() { - if (init_) { - init_ = false; - } else { - ++it_; - } - } - - void Reset() { - init_ = true; - it_ = rest_.begin(); - } - - private: - const W &first_; - const std::list &rest_; - bool init_; // in the initialized state? - typename std::list::const_iterator it_; -}; - -// Traverses union weight in backward direction. -template -class UnionWeightReverseIterator { - public: - explicit UnionWeightReverseIterator(const UnionWeight &weight) - : first_(weight.first_), - rest_(weight.rest_), - fin_(!first_.Member()), - it_(rest_.rbegin()) {} - - bool Done() const { return fin_; } - - const L &Value() const { return it_ == rest_.rend() ? first_ : *it_; } - - void Next() { - if (it_ == rest_.rend()) { - fin_ = true; - } else { - ++it_; - } - } - - void Reset() { - fin_ = !first_.Member(); - it_ = rest_.rbegin(); - } - - private: - const L &first_; - const std::list &rest_; - bool fin_; // in the final state? - typename std::list::const_reverse_iterator it_; -}; - -// UnionWeight member functions follow that require UnionWeightIterator. -template -inline std::istream &UnionWeight::Read(std::istream &istrm) { - Clear(); - int32_t size; - ReadType(istrm, &size); - for (int i = 0; i < size; ++i) { - W weight; - ReadType(istrm, &weight); - PushBack(weight, true); - } - return istrm; -} - -template -inline std::ostream &UnionWeight::Write(std::ostream &ostrm) const { - const int32_t size = Size(); - WriteType(ostrm, size); - for (UnionWeightIterator it(*this); !it.Done(); it.Next()) { - WriteType(ostrm, it.Value()); - } - return ostrm; -} - -template -inline bool UnionWeight::Member() const { - if (Size() <= 1) return true; - for (UnionWeightIterator it(*this); !it.Done(); it.Next()) { - if (!it.Value().Member()) return false; - } - return true; -} - -template -inline UnionWeight UnionWeight::Quantize(float delta) const { - UnionWeight weight; - for (UnionWeightIterator it(*this); !it.Done(); it.Next()) { - weight.PushBack(it.Value().Quantize(delta), true); - } - return weight; -} - -template -inline typename UnionWeight::ReverseWeight UnionWeight::Reverse() - const { - ReverseWeight weight; - for (UnionWeightIterator it(*this); !it.Done(); it.Next()) { - weight.PushBack(it.Value().Reverse(), false); - } - weight.Sort(); - return weight; -} - -template -inline size_t UnionWeight::Hash() const { - size_t h = 0; - static constexpr int lshift = 5; - static constexpr int rshift = CHAR_BIT * sizeof(size_t) - lshift; - for (UnionWeightIterator it(*this); !it.Done(); it.Next()) { - h = h << lshift ^ h >> rshift ^ it.Value().Hash(); - } - return h; -} - -// Requires union weight has been canonicalized. -template -inline bool operator==(const UnionWeight &w1, - const UnionWeight &w2) { - if (w1.Size() != w2.Size()) return false; - UnionWeightIterator it1(w1); - UnionWeightIterator it2(w2); - for (; !it1.Done(); it1.Next(), it2.Next()) { - if (it1.Value() != it2.Value()) return false; - } - return true; -} - -// Requires union weight has been canonicalized. -template -inline bool operator!=(const UnionWeight &w1, - const UnionWeight &w2) { - return !(w1 == w2); -} - -// Requires union weight has been canonicalized. -template -inline bool ApproxEqual(const UnionWeight &w1, - const UnionWeight &w2, float delta = kDelta) { - if (w1.Size() != w2.Size()) return false; - UnionWeightIterator it1(w1); - UnionWeightIterator it2(w2); - for (; !it1.Done(); it1.Next(), it2.Next()) { - if (!ApproxEqual(it1.Value(), it2.Value(), delta)) return false; - } - return true; -} - -template -inline std::ostream &operator<<(std::ostream &ostrm, - const UnionWeight &weight) { - UnionWeightIterator it(weight); - if (it.Done()) { - return ostrm << "EmptySet"; - } else if (!weight.Member()) { - return ostrm << "BadSet"; - } else { - CompositeWeightWriter writer(ostrm); - writer.WriteBegin(); - for (; !it.Done(); it.Next()) writer.WriteElement(it.Value()); - writer.WriteEnd(); - } - return ostrm; -} - -template -inline std::istream &operator>>(std::istream &istrm, - UnionWeight &weight) { - std::string s; - istrm >> s; - if (s == "EmptySet") { - weight = UnionWeight::Zero(); - } else if (s == "BadSet") { - weight = UnionWeight::NoWeight(); - } else { - weight = UnionWeight::Zero(); - std::istringstream sstrm(s); - CompositeWeightReader reader(sstrm); - reader.ReadBegin(); - bool more = true; - while (more) { - W v; - more = reader.ReadElement(&v); - weight.PushBack(v, true); - } - reader.ReadEnd(); - } - return istrm; -} - -template -inline UnionWeight Plus(const UnionWeight &w1, - const UnionWeight &w2) { - if (!w1.Member() || !w2.Member()) return UnionWeight::NoWeight(); - if (w1 == UnionWeight::Zero()) return w2; - if (w2 == UnionWeight::Zero()) return w1; - UnionWeightIterator it1(w1); - UnionWeightIterator it2(w2); - UnionWeight sum; - typename O::Compare comp; - while (!it1.Done() && !it2.Done()) { - const auto v1 = it1.Value(); - const auto v2 = it2.Value(); - if (comp(v1, v2)) { - sum.PushBack(v1, true); - it1.Next(); - } else { - sum.PushBack(v2, true); - it2.Next(); - } - } - for (; !it1.Done(); it1.Next()) sum.PushBack(it1.Value(), true); - for (; !it2.Done(); it2.Next()) sum.PushBack(it2.Value(), true); - return sum; -} - -template -inline UnionWeight Times(const UnionWeight &w1, - const UnionWeight &w2) { - if (!w1.Member() || !w2.Member()) return UnionWeight::NoWeight(); - if (w1 == UnionWeight::Zero() || w2 == UnionWeight::Zero()) { - return UnionWeight::Zero(); - } - UnionWeightIterator it1(w1); - UnionWeightIterator it2(w2); - UnionWeight prod1; - for (; !it1.Done(); it1.Next()) { - UnionWeight prod2; - for (; !it2.Done(); it2.Next()) { - prod2.PushBack(Times(it1.Value(), it2.Value()), true); - } - prod1 = Plus(prod1, prod2); - it2.Reset(); - } - return prod1; -} - -template -inline UnionWeight Divide(const UnionWeight &w1, - const UnionWeight &w2, DivideType typ) { - if (!w1.Member() || !w2.Member()) return UnionWeight::NoWeight(); - if (w1 == UnionWeight::Zero() || w2 == UnionWeight::Zero()) { - return UnionWeight::Zero(); - } - UnionWeightIterator it1(w1); - UnionWeightReverseIterator it2(w2); - UnionWeight quot; - if (w1.Size() == 1) { - for (; !it2.Done(); it2.Next()) { - quot.PushBack(Divide(it1.Value(), it2.Value(), typ), true); - } - } else if (w2.Size() == 1) { - for (; !it1.Done(); it1.Next()) { - quot.PushBack(Divide(it1.Value(), it2.Value(), typ), true); - } - } else { - quot = UnionWeight::NoWeight(); - } - return quot; -} - -// This function object generates weights over the union of weights for the -// underlying generators for the template weight types. This is intended -// primarily for testing. -template -class WeightGenerate> { - public: - using Weight = UnionWeight; - using Generate = WeightGenerate; - - explicit WeightGenerate(uint64_t seed = std::random_device()(), - bool allow_zero = true, - size_t num_random_weights = kNumRandomWeights) - : rand_(seed), - allow_zero_(allow_zero), - num_random_weights_(num_random_weights), - generate_(seed, false) {} - - Weight operator()() const { - const int sample = std::uniform_int_distribution<>( - 0, num_random_weights_ + allow_zero_ - 1)(rand_); - if (allow_zero_ && sample == num_random_weights_) { - return Weight::Zero(); - } else if (std::bernoulli_distribution(.5)(rand_)) { - return Weight(generate_()); - } else { - return Plus(Weight(generate_()), Weight(generate_())); - } - } - - private: - mutable std::mt19937_64 rand_; - const bool allow_zero_; - const size_t num_random_weights_; - const Generate generate_; -}; - -} // namespace fst - -#endif // FST_UNION_WEIGHT_H_ diff --git a/contrib/fstlib/fst/union.h b/contrib/fstlib/fst/union.h deleted file mode 100644 index 9359977..0000000 --- a/contrib/fstlib/fst/union.h +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions and classes to compute the union of two FSTs. - -#ifndef FST_UNION_H_ -#define FST_UNION_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace fst { - -// Computes the union (sum) of two FSTs. This version writes the union to an -// output MutableFst. If A transduces string x to y with weight a and B -// transduces string w to v with weight b, then their union transduces x to y -// with weight a and w to v with weight b. -// -// Complexity: -// -// Time: (V_2 + E_2) -// Space: O(V_2 + E_2) -// -// where Vi is the number of states, and Ei is the number of arcs, in the ith -// FST. -template -void Union(MutableFst *fst1, const Fst &fst2) { - // Checks for symbol table compatibility. - if (!CompatSymbols(fst1->InputSymbols(), fst2.InputSymbols()) || - !CompatSymbols(fst1->OutputSymbols(), fst2.OutputSymbols())) { - FSTERROR() << "Union: Input/output symbol tables of 1st argument " - << "do not match input/output symbol tables of 2nd argument"; - fst1->SetProperties(kError, kError); - return; - } - const auto numstates1 = fst1->NumStates(); - const bool initial_acyclic1 = - fst1->Properties(kInitialAcyclic, false) == kInitialAcyclic; - const auto props1 = fst1->Properties(kFstProperties, false); - const auto props2 = fst2.Properties(kFstProperties, false); - const auto start2 = fst2.Start(); - if (start2 == kNoStateId) { - if (props2 & kError) fst1->SetProperties(kError, kError); - return; - } - if (std::optional numstates2 = - fst2.NumStatesIfKnown()) { - fst1->ReserveStates(numstates1 + *numstates2 + (initial_acyclic1 ? 0 : 1)); - } - for (StateIterator> siter(fst2); !siter.Done(); siter.Next()) { - const auto s1 = fst1->AddState(); - const auto s2 = siter.Value(); - fst1->SetFinal(s1, fst2.Final(s2)); - fst1->ReserveArcs(s1, fst2.NumArcs(s2)); - for (ArcIterator> aiter(fst2, s2); !aiter.Done(); aiter.Next()) { - auto arc = aiter.Value(); // Copy intended. - arc.nextstate += numstates1; - fst1->AddArc(s1, std::move(arc)); - } - } - const auto start1 = fst1->Start(); - if (start1 == kNoStateId) { - fst1->SetStart(start2); - fst1->SetProperties(props2, kCopyProperties); - return; - } - if (initial_acyclic1) { - fst1->AddArc(start1, Arc(0, 0, start2 + numstates1)); - } else { - const auto nstart1 = fst1->AddState(); - fst1->SetStart(nstart1); - fst1->AddArc(nstart1, Arc(0, 0, start1)); - fst1->AddArc(nstart1, Arc(0, 0, start2 + numstates1)); - } - fst1->SetProperties(UnionProperties(props1, props2), kFstProperties); -} - -// Same as the above but can handle arbitrarily many right-hand-side FSTs, -// preallocating the states. -template -void Union(MutableFst *fst1, const std::vector *> &fsts2) { - // We add 1 just in case fst1 has an initial cycle. - fst1->ReserveStates(1 + fst1->NumStates() + CountStates(fsts2)); - for (const auto *fst2 : fsts2) Union(fst1, *fst2); -} - -// Computes the union of two FSTs, modifying the RationalFst argument. -template -void Union(RationalFst *fst1, const Fst &fst2) { - fst1->GetMutableImpl()->AddUnion(fst2); -} - -using UnionFstOptions = RationalFstOptions; - -// Computes the union (sum) of two FSTs. This version is a delayed FST. If A -// transduces string x to y with weight a and B transduces string w to v with -// weight b, then their union transduces x to y with weight a and w to v with -// weight b. -// -// Complexity: -// -// Time: O(v_1 + e_1 + v_2 + e_2) -// Space: O(v_1 + v_2) -// -// where vi is the number of states visited, and ei is the number of arcs -// visited, in the ith FST. Constant time and space to visit an input state or -// arc is assumed and exclusive of caching. -template -class UnionFst : public RationalFst { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - UnionFst(const Fst &fst1, const Fst &fst2) { - GetMutableImpl()->InitUnion(fst1, fst2); - } - - UnionFst(const Fst &fst1, const Fst &fst2, - const UnionFstOptions &opts) - : RationalFst(opts) { - GetMutableImpl()->InitUnion(fst1, fst2); - } - - // See Fst<>::Copy() for doc. - UnionFst(const UnionFst &fst, bool safe = false) - : RationalFst(fst, safe) {} - - // Gets a copy of this UnionFst. See Fst<>::Copy() for further doc. - UnionFst *Copy(bool safe = false) const override { - return new UnionFst(*this, safe); - } - - private: - using ImplToFst>::GetImpl; - using ImplToFst>::GetMutableImpl; -}; - -// Specialization for UnionFst. -template -class StateIterator> : public StateIterator> { - public: - explicit StateIterator(const UnionFst &fst) - : StateIterator>(fst) {} -}; - -// Specialization for UnionFst. -template -class ArcIterator> : public ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const UnionFst &fst, StateId s) - : ArcIterator>(fst, s) {} -}; - -using StdUnionFst = UnionFst; - -} // namespace fst - -#endif // FST_UNION_H_ diff --git a/contrib/fstlib/fst/util.h b/contrib/fstlib/fst/util.h deleted file mode 100644 index 5cb6721..0000000 --- a/contrib/fstlib/fst/util.h +++ /dev/null @@ -1,516 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST utility inline definitions. - -#ifndef FST_UTIL_H_ -#define FST_UTIL_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// Utility for error handling. - -DECLARE_bool(fst_error_fatal); - -#define FSTERROR() \ - (FST_FLAGS_fst_error_fatal ? LOG(FATAL) : LOG(ERROR)) - -namespace fst { - -// Utility for type I/O. For portability of serialized objects across -// architectures, care must be taken so that only fixed-size types (like -// `int32_t`) are used with `WriteType`/`ReadType`, not types that may differ in -// size depending on the architecture, such as `int`. For `enum` types, a -// fixed-size base (like `enum E : int32_t`) should be used. Objects are -// written and read in the host byte order, so will not be portable across -// different endiannesses. - -namespace internal { -// Whether the scalar type is supported by `ReadType`/`WriteType`. -template -inline constexpr bool IsScalarIOTypeV = - std::is_arithmetic_v || std::is_enum_v; -} // namespace internal - -// Reads types from an input stream. - -// Generic case. -template , T> * = nullptr> -inline std::istream &ReadType(std::istream &strm, T *t) { - return t->Read(strm); -} - -// Numeric (boolean, integral, floating-point) or enum case. -template , T> - * = nullptr> -inline std::istream &ReadType(std::istream &strm, T *t) { - return strm.read(reinterpret_cast(t), sizeof(T)); -} - -// Numeric (boolean, integral, floating-point) or enum case only. -template -inline std::istream &ReadType(std::istream &strm, size_t n, T *t) { - static_assert(internal::IsScalarIOTypeV, - "Type not supported for batch read."); - return strm.read(reinterpret_cast(t), sizeof(T) * n); -} - -// String case. -inline std::istream &ReadType(std::istream &strm, std::string *s) { - s->clear(); - int32_t ns = 0; - ReadType(strm, &ns); - if (ns <= 0) return strm; - s->resize(ns); - ReadType(strm, ns, s->data()); - return strm; -} - -// Declares types that can be read from an input stream. -template -std::istream &ReadType(std::istream &strm, std::vector *c); -template -std::istream &ReadType(std::istream &strm, std::list *c); -template -std::istream &ReadType(std::istream &strm, std::set *c); -template -std::istream &ReadType(std::istream &strm, std::map *c); -template -std::istream &ReadType(std::istream &strm, std::unordered_map *c); -template -std::istream &ReadType(std::istream &strm, std::unordered_set *c); - -// Pair case. -template -inline std::istream &ReadType(std::istream &strm, std::pair *p) { - ReadType(strm, &p->first); - ReadType(strm, &p->second); - return strm; -} - -template -inline std::istream &ReadType(std::istream &strm, std::pair *p) { - ReadType(strm, const_cast(&p->first)); - ReadType(strm, &p->second); - return strm; -} - -namespace internal { -template -std::istream &ReadContainerType(std::istream &strm, C *c, ReserveFn reserve) { - c->clear(); - int64_t n = 0; - ReadType(strm, &n); - reserve(c, n); - auto insert = std::inserter(*c, c->begin()); - for (int64_t i = 0; i < n; ++i) { - typename C::value_type value; - ReadType(strm, &value); - *insert = value; - } - return strm; -} - -// Generic vector case. -template , T> * = nullptr> -inline std::istream &ReadVectorType(std::istream &strm, std::vector *c) { - return internal::ReadContainerType( - strm, c, [](decltype(c) v, int n) { v->reserve(n); }); -} - -// Vector of numerics (boolean, integral, floating-point, char) or enum case. -template < - typename T, class A, - typename std::enable_if_t, T> * = nullptr> -inline std::istream &ReadVectorType(std::istream &strm, std::vector *c) { - c->clear(); - int64_t n = 0; - ReadType(strm, &n); - if (n == 0) return strm; - c->resize(n); - ReadType(strm, n, c->data()); - return strm; -} -} // namespace internal - -template -std::istream &ReadType(std::istream &strm, std::array *c) { - if constexpr (internal::IsScalarIOTypeV) { - ReadType(strm, c->size(), c->data()); - } else { - for (auto &v : *c) ReadType(strm, &v); - } - return strm; -} - -template -std::istream &ReadType(std::istream &strm, std::vector *c) { - return internal::ReadVectorType(strm, c); -} - -template -std::istream &ReadType(std::istream &strm, std::list *c) { - return internal::ReadContainerType(strm, c, [](decltype(c) v, int n) {}); -} - -template -std::istream &ReadType(std::istream &strm, std::set *c) { - return internal::ReadContainerType(strm, c, [](decltype(c) v, int n) {}); -} - -template -std::istream &ReadType(std::istream &strm, std::map *c) { - return internal::ReadContainerType(strm, c, [](decltype(c) v, int n) {}); -} - -template -std::istream &ReadType(std::istream &strm, std::unordered_set *c) { - return internal::ReadContainerType( - strm, c, [](decltype(c) v, int n) { v->reserve(n); }); -} - -template -std::istream &ReadType(std::istream &strm, std::unordered_map *c) { - return internal::ReadContainerType( - strm, c, [](decltype(c) v, int n) { v->reserve(n); }); -} - -// Writes types to an output stream. - -// Generic case. -template ::value && - // `string_view` is handled separately below. - !std::is_convertible::value, - T>::type * = nullptr> -inline std::ostream &WriteType(std::ostream &strm, const T t) { - t.Write(strm); - return strm; -} - -// Numeric (boolean, integral, floating-point) or enum case. -template , T> - * = nullptr> -inline std::ostream &WriteType(std::ostream &strm, const T t) { - return strm.write(reinterpret_cast(&t), sizeof(T)); -} - -// Numeric (boolean, integral, floating-point) or enum case only. -template -inline std::ostream &WriteType(std::ostream &strm, size_t n, const T *t) { - static_assert(internal::IsScalarIOTypeV, - "Type not supported for batch write."); - return strm.write(reinterpret_cast(t), sizeof(T) * n); -} - -inline std::ostream &WriteType(std::ostream &strm, std::string_view s) { - int32_t ns = s.size(); - WriteType(strm, ns); - return strm.write(s.data(), ns); -} - -// Declares types that can be written to an output stream. - -template -std::ostream &WriteType(std::ostream &strm, const std::vector &c); - -template -std::ostream &WriteType(std::ostream &strm, const std::list &c); - -template -std::ostream &WriteType(std::ostream &strm, const std::set &c); - -template -std::ostream &WriteType(std::ostream &strm, const std::map &c); - -template -std::ostream &WriteType(std::ostream &strm, const std::unordered_map &c); - -template -std::ostream &WriteType(std::ostream &strm, const std::unordered_set &c); - -// Pair case. -template -inline std::ostream &WriteType(std::ostream &strm, const std::pair &p) { - WriteType(strm, p.first); - WriteType(strm, p.second); - return strm; -} - -namespace internal { -template -std::ostream &WriteSequence(std::ostream &strm, const C &c) { - for (const auto &e : c) { - WriteType(strm, e); - } - return strm; -} - -template -std::ostream &WriteContainer(std::ostream &strm, const C &c) { - const int64_t n = c.size(); - WriteType(strm, n); - WriteSequence(strm, c); - return strm; -} -} // namespace internal - -template -std::ostream &WriteType(std::ostream &strm, const std::array &c) { - return internal::WriteSequence(strm, c); -} - -template -std::ostream &WriteType(std::ostream &strm, const std::vector &c) { - return internal::WriteContainer(strm, c); -} - -template -std::ostream &WriteType(std::ostream &strm, const std::list &c) { - return internal::WriteContainer(strm, c); -} - -template -std::ostream &WriteType(std::ostream &strm, const std::set &c) { - return internal::WriteContainer(strm, c); -} - -template -std::ostream &WriteType(std::ostream &strm, const std::map &c) { - return internal::WriteContainer(strm, c); -} - -template -std::ostream &WriteType(std::ostream &strm, const std::unordered_map &c) { - return internal::WriteContainer(strm, c); -} - -template -std::ostream &WriteType(std::ostream &strm, const std::unordered_set &c) { - return internal::WriteContainer(strm, c); -} - -// Utilities for converting between int64_t or Weight and string. - -// Parses a 64-bit signed integer in some base out of an input string. The -// string should consist only of digits (no prefixes such as "0x") and an -// optionally preceding minus. Returns a value iff the entirety of the string is -// consumed during integer parsing, otherwise returns `std::nullopt`. -std::optional ParseInt64(std::string_view s, int base = 10); - -int64_t StrToInt64(std::string_view s, std::string_view source, size_t nline, - bool * error = nullptr); - -template -Weight StrToWeight(std::string_view s) { - Weight w; - std::istringstream strm(std::string{s}); - strm >> w; - if (!strm) { - FSTERROR() << "StrToWeight: Bad weight: " << s; - return Weight::NoWeight(); - } - return w; -} - -template -std::string WeightToStr(Weight w) { - std::ostringstream strm; - strm.precision(9); - strm << w; - return strm.str(); -} - -// Utilities for reading/writing integer pairs (typically labels). - -template -bool ReadIntPairs(std::string_view source, - std::vector> *pairs) { - std::ifstream strm(std::string(source), std::ios_base::in); - if (!strm) { - LOG(ERROR) << "ReadIntPairs: Can't open file: " << source; - return false; - } - const int kLineLen = 8096; - char line[kLineLen]; - size_t nline = 0; - pairs->clear(); - while (strm.getline(line, kLineLen)) { - ++nline; - std::vector col = - StrSplit(line, ByAnyChar("\n\t "), SkipEmpty()); - // empty line or comment? - if (col.empty() || col[0].empty() || col[0][0] == '#') continue; - if (col.size() != 2) { - LOG(ERROR) << "ReadIntPairs: Bad number of columns, " - << "file = " << source << ", line = " << nline; - return false; - } - bool err; - I i1 = StrToInt64(col[0], source, nline, &err); - if (err) return false; - I i2 = StrToInt64(col[1], source, nline, &err); - if (err) return false; - pairs->emplace_back(i1, i2); - } - return true; -} - -template -bool WriteIntPairs(std::string_view source, - const std::vector> &pairs) { - std::ofstream fstrm; - if (!source.empty()) { - fstrm.open(std::string(source)); - if (!fstrm) { - LOG(ERROR) << "WriteIntPairs: Can't open file: " << source; - return false; - } - } - std::ostream &ostrm = fstrm.is_open() ? fstrm : std::cout; - for (const auto &pair : pairs) { - ostrm << pair.first << "\t" << pair.second << "\n"; - } - return !!ostrm; -} - -// Utilities for reading/writing label pairs. - -template -bool ReadLabelPairs(std::string_view source, - std::vector> *pairs) { - return ReadIntPairs(source, pairs); -} - -template -bool WriteLabelPairs(std::string_view source, - const std::vector> &pairs) { - return WriteIntPairs(source, pairs); -} - -// Utilities for converting a type name to a legal C symbol. - -void ConvertToLegalCSymbol(std::string *s); - -// Utilities for stream I/O. - -bool AlignInput(std::istream &strm, size_t align = MappedFile::kArchAlignment); -bool AlignOutput(std::ostream &strm, size_t align = MappedFile::kArchAlignment); - -// An associative container for which testing membership is faster than an STL -// set if members are restricted to an interval that excludes most non-members. -// A Key must have ==, !=, and < operators defined. Element NoKey should be a -// key that marks an uninitialized key and is otherwise unused. Find() returns -// an STL const_iterator to the match found, otherwise it equals End(). -template -class CompactSet { - public: - using const_iterator = typename std::set::const_iterator; - - CompactSet() : min_key_(NoKey), max_key_(NoKey) {} - - CompactSet(const CompactSet &) = default; - - void Insert(Key key) { - set_.insert(key); - if (min_key_ == NoKey || key < min_key_) min_key_ = key; - if (max_key_ == NoKey || max_key_ < key) max_key_ = key; - } - - void Erase(Key key) { - set_.erase(key); - if (set_.empty()) { - min_key_ = max_key_ = NoKey; - } else if (key == min_key_) { - ++min_key_; - } else if (key == max_key_) { - --max_key_; - } - } - - void Clear() { - set_.clear(); - min_key_ = max_key_ = NoKey; - } - - const_iterator Find(Key key) const { - if (min_key_ == NoKey || key < min_key_ || max_key_ < key) { - return set_.end(); - } else { - return set_.find(key); - } - } - - bool Member(Key key) const { - if (min_key_ == NoKey || key < min_key_ || max_key_ < key) { - return false; // out of range - } else if (min_key_ != NoKey && max_key_ + 1 == min_key_ + set_.size()) { - return true; // dense range - } else { - return set_.count(key); - } - } - - const_iterator Begin() const { return set_.begin(); } - - const_iterator End() const { return set_.end(); } - - // All stored keys are greater than or equal to this value. - Key LowerBound() const { return min_key_; } - - // All stored keys are less than or equal to this value. - Key UpperBound() const { return max_key_; } - - private: - std::set set_; - Key min_key_; - Key max_key_; - - void operator=(const CompactSet &) = delete; -}; - -} // namespace fst - -#endif // FST_UTIL_H_ diff --git a/contrib/fstlib/fst/vector-fst.h b/contrib/fstlib/fst/vector-fst.h deleted file mode 100644 index f01e7f0..0000000 --- a/contrib/fstlib/fst/vector-fst.h +++ /dev/null @@ -1,828 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Simple concrete, mutable FST whose states and arcs are stored in STL vectors. - -#ifndef FST_VECTOR_FST_H_ -#define FST_VECTOR_FST_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include // For optional argument declarations -#include -#include -#include -#include -#include - -namespace fst { - -template -class VectorFst; - -template -void Cast(const F &, G *); - -// Arcs (of type A) implemented by an STL vector per state. M specifies Arc -// allocator (default declared in fst-decl.h). -template */> -class VectorState { - public: - using Arc = A; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - using ArcAllocator = M; - using StateAllocator = typename std::allocator_traits< - ArcAllocator>::template rebind_alloc>; - - // Provide STL allocator for arcs. - explicit VectorState(const ArcAllocator &alloc) : arcs_(alloc) {} - - VectorState(const VectorState &state, const ArcAllocator &alloc) - : final_weight_(state.Final()), - niepsilons_(state.NumInputEpsilons()), - noepsilons_(state.NumOutputEpsilons()), - arcs_(state.arcs_.begin(), state.arcs_.end(), alloc) {} - - void Reset() { - final_weight_ = Weight::Zero(); - niepsilons_ = 0; - noepsilons_ = 0; - arcs_.clear(); - } - - Weight Final() const { return final_weight_; } - - size_t NumInputEpsilons() const { return niepsilons_; } - - size_t NumOutputEpsilons() const { return noepsilons_; } - - size_t NumArcs() const { return arcs_.size(); } - - const Arc &GetArc(size_t n) const { return arcs_[n]; } - - const Arc *Arcs() const { return !arcs_.empty() ? &arcs_[0] : nullptr; } - - Arc *MutableArcs() { return !arcs_.empty() ? &arcs_[0] : nullptr; } - - void ReserveArcs(size_t n) { arcs_.reserve(n); } - - void SetFinal(Weight weight) { final_weight_ = std::move(weight); } - - void SetNumInputEpsilons(size_t n) { niepsilons_ = n; } - - void SetNumOutputEpsilons(size_t n) { noepsilons_ = n; } - - void AddArc(const Arc &arc) { - IncrementNumEpsilons(arc); - arcs_.push_back(arc); - } - - void AddArc(Arc &&arc) { - IncrementNumEpsilons(arc); - arcs_.push_back(std::move(arc)); - } - - template - void EmplaceArc(T &&...ctor_args) { - arcs_.emplace_back(std::forward(ctor_args)...); - IncrementNumEpsilons(arcs_.back()); - } - - void SetArc(const Arc &arc, size_t n) { - if (arcs_[n].ilabel == 0) --niepsilons_; - if (arcs_[n].olabel == 0) --noepsilons_; - IncrementNumEpsilons(arc); - arcs_[n] = arc; - } - - void DeleteArcs() { - niepsilons_ = 0; - noepsilons_ = 0; - arcs_.clear(); - } - - void DeleteArcs(size_t n) { - for (size_t i = 0; i < n; ++i) { - if (arcs_.back().ilabel == 0) --niepsilons_; - if (arcs_.back().olabel == 0) --noepsilons_; - arcs_.pop_back(); - } - } - - // For state class allocation. - void *operator new(size_t size, StateAllocator *alloc) { - return alloc->allocate(1); - } - - // For state destruction and memory freeing. - static void Destroy(VectorState *state, StateAllocator *alloc) { - if (state) { - state->~VectorState(); - alloc->deallocate(state, 1); - } - } - - private: - // Update the number of epsilons as a result of having added an arc. - void IncrementNumEpsilons(const Arc &arc) { - if (arc.ilabel == 0) ++niepsilons_; - if (arc.olabel == 0) ++noepsilons_; - } - - Weight final_weight_ = Weight::Zero(); // Final weight. - size_t niepsilons_ = 0; // # of input epsilons - size_t noepsilons_ = 0; // # of output epsilons - std::vector arcs_; // Arc container. -}; - -namespace internal { - -// States are implemented by STL vectors, templated on the -// State definition. This does not manage the Fst properties. -template -class VectorFstBaseImpl : public FstImpl { - public: - using State = S; - using Arc = typename State::Arc; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - VectorFstBaseImpl() = default; - - ~VectorFstBaseImpl() override { - for (auto *state : states_) State::Destroy(state, &state_alloc_); - } - - // Copying is not permitted. - VectorFstBaseImpl(const VectorFstBaseImpl &) = delete; - VectorFstBaseImpl &operator=(const VectorFstBaseImpl &) = delete; - - // Moving is permitted. - VectorFstBaseImpl(VectorFstBaseImpl &&impl) noexcept - : FstImpl(), - states_(std::move(impl.states_)), - start_(impl.start_) { - impl.states_.clear(); - impl.start_ = kNoStateId; - } - - VectorFstBaseImpl &operator=(VectorFstBaseImpl &&impl) noexcept { - for (auto *state : states_) { - State::Destroy(state, &state_alloc_); - } - states_.clear(); - std::swap(states_, impl.states_); - start_ = impl.start_; - impl.start_ = kNoStateId; - return *this; - } - - StateId Start() const { return start_; } - - Weight Final(StateId state) const { return states_[state]->Final(); } - - StateId NumStates() const { return states_.size(); } - - size_t NumArcs(StateId state) const { return states_[state]->NumArcs(); } - - size_t NumInputEpsilons(StateId state) const { - return GetState(state)->NumInputEpsilons(); - } - - size_t NumOutputEpsilons(StateId state) const { - return GetState(state)->NumOutputEpsilons(); - } - - void SetStart(StateId state) { start_ = state; } - - void SetFinal(StateId state, Weight weight) { - states_[state]->SetFinal(std::move(weight)); - } - - StateId AddState(State *state) { - states_.push_back(state); - return states_.size() - 1; - } - - StateId AddState() { return AddState(CreateState()); } - - void AddStates(size_t n) { - const auto curr_num_states = NumStates(); - states_.resize(n + curr_num_states); - std::generate(states_.begin() + curr_num_states, states_.end(), - [this] { return CreateState(); }); - } - - void AddArc(StateId state, const Arc &arc) { states_[state]->AddArc(arc); } - - void AddArc(StateId state, Arc &&arc) { - states_[state]->AddArc(std::move(arc)); - } - - template - void EmplaceArc(StateId state, T &&...ctor_args) { - states_[state]->EmplaceArc(std::forward(ctor_args)...); - } - - void DeleteStates(const std::vector &dstates) { - std::vector newid(states_.size(), 0); - for (size_t i = 0; i < dstates.size(); ++i) newid[dstates[i]] = kNoStateId; - StateId nstates = 0; - for (StateId state = 0; state < states_.size(); ++state) { - if (newid[state] != kNoStateId) { - newid[state] = nstates; - if (state != nstates) states_[nstates] = states_[state]; - ++nstates; - } else { - State::Destroy(states_[state], &state_alloc_); - } - } - states_.resize(nstates); - for (StateId state = 0; state < states_.size(); ++state) { - auto *arcs = states_[state]->MutableArcs(); - size_t narcs = 0; - auto nieps = states_[state]->NumInputEpsilons(); - auto noeps = states_[state]->NumOutputEpsilons(); - for (size_t i = 0; i < states_[state]->NumArcs(); ++i) { - const auto t = newid[arcs[i].nextstate]; - if (t != kNoStateId) { - arcs[i].nextstate = t; - if (i != narcs) arcs[narcs] = arcs[i]; - ++narcs; - } else { - if (arcs[i].ilabel == 0) --nieps; - if (arcs[i].olabel == 0) --noeps; - } - } - states_[state]->DeleteArcs(states_[state]->NumArcs() - narcs); - states_[state]->SetNumInputEpsilons(nieps); - states_[state]->SetNumOutputEpsilons(noeps); - } - if (Start() != kNoStateId) SetStart(newid[Start()]); - } - - void DeleteStates() { - for (size_t state = 0; state < states_.size(); ++state) { - State::Destroy(states_[state], &state_alloc_); - } - states_.clear(); - SetStart(kNoStateId); - } - - void DeleteArcs(StateId state, size_t n) { states_[state]->DeleteArcs(n); } - - void DeleteArcs(StateId state) { states_[state]->DeleteArcs(); } - - State *GetState(StateId state) { return states_[state]; } - - const State *GetState(StateId state) const { return states_[state]; } - - void SetState(StateId state, State *vstate) { states_[state] = vstate; } - - void ReserveStates(size_t n) { states_.reserve(n); } - - void ReserveArcs(StateId state, size_t n) { states_[state]->ReserveArcs(n); } - - // Provide information needed for generic state iterator. - void InitStateIterator(StateIteratorData *data) const { - data->base = nullptr; - data->nstates = states_.size(); - } - - // Provide information needed for generic arc iterator. - void InitArcIterator(StateId state, ArcIteratorData *data) const { - data->base = nullptr; - data->narcs = states_[state]->NumArcs(); - data->arcs = states_[state]->Arcs(); - data->ref_count = nullptr; - } - - private: - State *CreateState() { return new (&state_alloc_) State(arc_alloc_); } - - std::vector states_; - StateId start_ = kNoStateId; - typename State::StateAllocator state_alloc_; - typename State::ArcAllocator arc_alloc_; -}; - -// This is a VectorFstBaseImpl container that holds VectorStates and manages FST -// properties. -template -class VectorFstImpl : public VectorFstBaseImpl { - public: - using State = S; - using Arc = typename State::Arc; - using Label = typename Arc::Label; - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - using FstImpl::SetInputSymbols; - using FstImpl::SetOutputSymbols; - using FstImpl::SetType; - using FstImpl::SetProperties; - using FstImpl::Properties; - - using VectorFstBaseImpl::Start; - using VectorFstBaseImpl::NumStates; - using VectorFstBaseImpl::GetState; - using VectorFstBaseImpl::ReserveArcs; - - friend class MutableArcIterator>; - - using BaseImpl = VectorFstBaseImpl; - - VectorFstImpl() { - SetType("vector"); - SetProperties(kNullProperties | kStaticProperties); - } - - explicit VectorFstImpl(const Fst &fst); - - static VectorFstImpl *Read(std::istream &strm, const FstReadOptions &opts); - - void SetStart(StateId state) { - BaseImpl::SetStart(state); - SetProperties(SetStartProperties(Properties())); - } - - void SetFinal(StateId state, Weight weight) { - const auto old_weight = BaseImpl::Final(state); - const auto properties = - SetFinalProperties(Properties(), old_weight, weight); - BaseImpl::SetFinal(state, std::move(weight)); - SetProperties(properties); - } - - StateId AddState() { - const auto state = BaseImpl::AddState(); - SetProperties(AddStateProperties(Properties())); - return state; - } - - void AddStates(size_t n) { - BaseImpl::AddStates(n); - SetProperties(AddStateProperties(Properties())); - } - - void AddArc(StateId state, const Arc &arc) { - BaseImpl::AddArc(state, arc); - UpdatePropertiesAfterAddArc(state); - } - - void AddArc(StateId state, Arc &&arc) { - BaseImpl::AddArc(state, std::move(arc)); - UpdatePropertiesAfterAddArc(state); - } - - template - void EmplaceArc(StateId state, T &&...ctor_args) { - BaseImpl::EmplaceArc(state, std::forward(ctor_args)...); - UpdatePropertiesAfterAddArc(state); - } - - void DeleteStates(const std::vector &dstates) { - BaseImpl::DeleteStates(dstates); - SetProperties(DeleteStatesProperties(Properties())); - } - - void DeleteStates() { - BaseImpl::DeleteStates(); - SetProperties(DeleteAllStatesProperties(Properties(), kStaticProperties)); - } - - void DeleteArcs(StateId state, size_t n) { - BaseImpl::DeleteArcs(state, n); - SetProperties(DeleteArcsProperties(Properties())); - } - - void DeleteArcs(StateId state) { - BaseImpl::DeleteArcs(state); - SetProperties(DeleteArcsProperties(Properties())); - } - - // Properties always true of this FST class - static constexpr uint64_t kStaticProperties = kExpanded | kMutable; - - private: - void UpdatePropertiesAfterAddArc(StateId state) { - auto *vstate = GetState(state); - const size_t num_arcs{vstate->NumArcs()}; - if (num_arcs) { - const auto &arc = vstate->GetArc(num_arcs - 1); - const auto *parc = - (num_arcs < 2) ? nullptr : &(vstate->GetArc(num_arcs - 2)); - SetProperties(AddArcProperties(Properties(), state, arc, parc)); - } - } - - // Minimum file format version supported. - static constexpr int kMinFileVersion = 2; -}; - -template -VectorFstImpl::VectorFstImpl(const Fst &fst) { - SetType("vector"); - SetInputSymbols(fst.InputSymbols()); - SetOutputSymbols(fst.OutputSymbols()); - BaseImpl::SetStart(fst.Start()); - if (std::optional num_states = fst.NumStatesIfKnown()) { - BaseImpl::ReserveStates(*num_states); - } - for (StateIterator> siter(fst); !siter.Done(); siter.Next()) { - const auto state = siter.Value(); - BaseImpl::AddState(); - BaseImpl::SetFinal(state, fst.Final(state)); - ReserveArcs(state, fst.NumArcs(state)); - for (ArcIterator> aiter(fst, state); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - BaseImpl::AddArc(state, arc); - } - } - SetProperties(fst.Properties(kCopyProperties, false) | kStaticProperties); -} - -template -VectorFstImpl *VectorFstImpl::Read(std::istream &strm, - const FstReadOptions &opts) { - auto impl = std::make_unique(); - FstHeader hdr; - if (!impl->ReadHeader(strm, opts, kMinFileVersion, &hdr)) return nullptr; - impl->BaseImpl::SetStart(hdr.Start()); - if (hdr.NumStates() != kNoStateId) impl->ReserveStates(hdr.NumStates()); - StateId state = 0; - for (; hdr.NumStates() == kNoStateId || state < hdr.NumStates(); ++state) { - Weight weight; - if (!weight.Read(strm)) break; - impl->BaseImpl::AddState(); - auto *vstate = impl->GetState(state); - vstate->SetFinal(weight); - int64_t narcs; - ReadType(strm, &narcs); - if (!strm) { - LOG(ERROR) << "VectorFst::Read: Read failed: " << opts.source; - return nullptr; - } - impl->ReserveArcs(state, narcs); - for (int64_t i = 0; i < narcs; ++i) { - Arc arc; - ReadType(strm, &arc.ilabel); - ReadType(strm, &arc.olabel); - arc.weight.Read(strm); - ReadType(strm, &arc.nextstate); - if (!strm) { - LOG(ERROR) << "VectorFst::Read: Read failed: " << opts.source; - return nullptr; - } - impl->BaseImpl::AddArc(state, std::move(arc)); - } - } - if (hdr.NumStates() != kNoStateId && state != hdr.NumStates()) { - LOG(ERROR) << "VectorFst::Read: Unexpected end of file: " << opts.source; - return nullptr; - } - return impl.release(); -} - -} // namespace internal - -// Simple concrete, mutable FST. This class attaches interface to implementation -// and handles reference counting, delegating most methods to ImplToMutableFst. -// Also supports ReserveStates and ReserveArcs methods (cf. STL vector methods). -// The second optional template argument gives the State definition. -// -// VectorFst is thread-compatible. -template */> -class VectorFst : public ImplToMutableFst> { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using State = S; - using Impl = internal::VectorFstImpl; - - friend class StateIterator>; - friend class ArcIterator>; - friend class MutableArcIterator>; - - template - friend void Cast(const F &, G *); - - VectorFst() : ImplToMutableFst(std::make_shared()) {} - - explicit VectorFst(const Fst &fst) - : ImplToMutableFst(std::make_shared(fst)) {} - - VectorFst(const VectorFst &fst, bool unused_safe = false) - : ImplToMutableFst(fst.GetSharedImpl()) {} - - VectorFst(VectorFst &&) noexcept; - - // Get a copy of this VectorFst. See Fst<>::Copy() for further doc. - VectorFst *Copy(bool safe = false) const override { - return new VectorFst(*this, safe); - } - - VectorFst &operator=(const VectorFst &) = default; - - VectorFst &operator=(VectorFst &&) noexcept; - - VectorFst &operator=(const Fst &fst) override { - if (this != &fst) SetImpl(std::make_shared(fst)); - return *this; - } - - template - void EmplaceArc(StateId state, T &&...ctor_args) { - MutateCheck(); - GetMutableImpl()->EmplaceArc(state, std::forward(ctor_args)...); - } - - // Reads a VectorFst from an input stream, returning nullptr on error. - static VectorFst *Read(std::istream &strm, const FstReadOptions &opts) { - auto *impl = Impl::Read(strm, opts); - return impl ? new VectorFst(std::shared_ptr(impl)) : nullptr; - } - - // Read a VectorFst from a file, returning nullptr on error; empty source - // reads from standard input. - static VectorFst *Read(std::string_view source) { - auto *impl = ImplToExpandedFst>::Read(source); - return impl ? new VectorFst(std::shared_ptr(impl)) : nullptr; - } - - bool Write(std::ostream &strm, const FstWriteOptions &opts) const override { - return WriteFst(*this, strm, opts); - } - - bool Write(const std::string &source) const override { - return Fst::WriteFile(source); - } - - template - static bool WriteFst(const FST &fst, std::ostream &strm, - const FstWriteOptions &opts); - - void InitStateIterator(StateIteratorData *data) const override { - GetImpl()->InitStateIterator(data); - } - - void InitArcIterator(StateId s, ArcIteratorData *data) const override { - GetImpl()->InitArcIterator(s, data); - } - - inline void InitMutableArcIterator(StateId s, - MutableArcIteratorData *) override; - - using ImplToMutableFst>::ReserveArcs; - using ImplToMutableFst>::ReserveStates; - - private: - using ImplToMutableFst>::GetImpl; - using ImplToMutableFst>::GetMutableImpl; - using ImplToMutableFst>::MutateCheck; - using ImplToMutableFst>::SetImpl; - - explicit VectorFst(std::shared_ptr impl) - : ImplToMutableFst(impl) {} -}; - -template -inline VectorFst::VectorFst(VectorFst &&fst) noexcept = default; - -template -inline VectorFst &VectorFst::operator=( - VectorFst &&fst) noexcept = default; - -// Writes FST to file in Vector format, potentially with a pass over the machine -// before writing to compute number of states. -template -template -bool VectorFst::WriteFst(const FST &fst, std::ostream &strm, - const FstWriteOptions &opts) { - static constexpr int file_version = 2; - bool update_header = true; - FstHeader hdr; - hdr.SetStart(fst.Start()); - hdr.SetNumStates(kNoStateId); - std::streampos start_offset = 0; - if (fst.Properties(kExpanded, false) || opts.stream_write || - (start_offset = strm.tellp()) != -1) { - hdr.SetNumStates(CountStates(fst)); - update_header = false; - } - const auto properties = - fst.Properties(kCopyProperties, false) | Impl::kStaticProperties; - internal::FstImpl::WriteFstHeader(fst, strm, opts, file_version, - "vector", properties, &hdr); - StateId num_states = 0; - for (StateIterator siter(fst); !siter.Done(); siter.Next()) { - const auto s = siter.Value(); - fst.Final(s).Write(strm); - const int64_t narcs = fst.NumArcs(s); - WriteType(strm, narcs); - for (ArcIterator aiter(fst, s); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - WriteType(strm, arc.ilabel); - WriteType(strm, arc.olabel); - arc.weight.Write(strm); - WriteType(strm, arc.nextstate); - } - ++num_states; - } - strm.flush(); - if (!strm) { - LOG(ERROR) << "VectorFst::Write: Write failed: " << opts.source; - return false; - } - if (update_header) { - hdr.SetNumStates(num_states); - return internal::FstImpl::UpdateFstHeader( - fst, strm, opts, file_version, "vector", properties, &hdr, - start_offset); - } else { - if (num_states != hdr.NumStates()) { - LOG(ERROR) << "Inconsistent number of states observed during write"; - return false; - } - } - return true; -} - -// Specialization for VectorFst; see generic version in fst.h for sample usage -// (but use the VectorFst type instead). This version should inline. -template -class StateIterator> { - public: - using StateId = typename Arc::StateId; - - explicit StateIterator(const VectorFst &fst) - : nstates_(fst.GetImpl()->NumStates()) {} - - bool Done() const { return s_ >= nstates_; } - - StateId Value() const { return s_; } - - void Next() { ++s_; } - - void Reset() { s_ = 0; } - - private: - const StateId nstates_; - StateId s_ = 0; -}; - -// Specialization for VectorFst; see generic version in fst.h for sample usage -// (but use the VectorFst type instead). This version should inline. -template -class ArcIterator> { - public: - using StateId = typename Arc::StateId; - - ArcIterator(const VectorFst &fst, StateId s) - : arcs_(fst.GetImpl()->GetState(s)->Arcs()), - narcs_(fst.GetImpl()->GetState(s)->NumArcs()) {} - - bool Done() const { return i_ >= narcs_; } - - const Arc &Value() const { return arcs_[i_]; } - - void Next() { ++i_; } - - void Reset() { i_ = 0; } - - void Seek(size_t a) { i_ = a; } - - size_t Position() const { return i_; } - - constexpr uint8_t Flags() const { return kArcValueFlags; } - - void SetFlags(uint8_t, uint8_t) {} - - private: - const Arc *arcs_; - size_t narcs_; - size_t i_ = 0; -}; - -// Specialization for VectorFst; see generic version in mutable-fst.h for sample -// usage (but use the VectorFst type instead). This version should inline. -template -class MutableArcIterator> - : public MutableArcIteratorBase { - public: - using StateId = typename Arc::StateId; - using Weight = typename Arc::Weight; - - MutableArcIterator(VectorFst *fst, StateId s) { - fst->MutateCheck(); - state_ = fst->GetMutableImpl()->GetState(s); - properties_ = &fst->GetImpl()->properties_; - } - - bool Done() const final { return i_ >= state_->NumArcs(); } - - const Arc &Value() const final { return state_->GetArc(i_); } - - void Next() final { ++i_; } - - size_t Position() const final { return i_; } - - void Reset() final { i_ = 0; } - - void Seek(size_t a) final { i_ = a; } - - void SetValue(const Arc &arc) final { - const auto &oarc = state_->GetArc(i_); - uint64_t properties = properties_->load(std::memory_order_relaxed); - if (oarc.ilabel != oarc.olabel) properties &= ~kNotAcceptor; - if (oarc.ilabel == 0) { - properties &= ~kIEpsilons; - if (oarc.olabel == 0) properties &= ~kEpsilons; - } - if (oarc.olabel == 0) properties &= ~kOEpsilons; - if (oarc.weight != Weight::Zero() && oarc.weight != Weight::One()) { - properties &= ~kWeighted; - } - state_->SetArc(arc, i_); - if (arc.ilabel != arc.olabel) { - properties |= kNotAcceptor; - properties &= ~kAcceptor; - } - if (arc.ilabel == 0) { - properties |= kIEpsilons; - properties &= ~kNoIEpsilons; - if (arc.olabel == 0) { - properties |= kEpsilons; - properties &= ~kNoEpsilons; - } - } - if (arc.olabel == 0) { - properties |= kOEpsilons; - properties &= ~kNoOEpsilons; - } - if (arc.weight != Weight::Zero() && arc.weight != Weight::One()) { - properties |= kWeighted; - properties &= ~kUnweighted; - } - properties &= kSetArcProperties | kAcceptor | kNotAcceptor | kEpsilons | - kNoEpsilons | kIEpsilons | kNoIEpsilons | kOEpsilons | - kNoOEpsilons | kWeighted | kUnweighted; - properties_->store(properties, std::memory_order_relaxed); - } - - uint8_t Flags() const final { return kArcValueFlags; } - - void SetFlags(uint8_t, uint8_t) final {} - - private: - State *state_; - std::atomic *properties_; - size_t i_ = 0; -}; - -// Provides information needed for the generic mutable arc iterator. -template -inline void VectorFst::InitMutableArcIterator( - StateId s, MutableArcIteratorData *data) { - data->base = - std::make_unique>>(this, s); -} - -// A useful alias when using StdArc. -using StdVectorFst = VectorFst; - -} // namespace fst - -#endif // FST_VECTOR_FST_H_ diff --git a/contrib/fstlib/fst/verify.h b/contrib/fstlib/fst/verify.h deleted file mode 100644 index 3a07dd9..0000000 --- a/contrib/fstlib/fst/verify.h +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Function to verify an FST's contents. - -#ifndef FST_VERIFY_H_ -#define FST_VERIFY_H_ - -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -// Verifies that an Fst's contents are sane. -template -bool Verify(const Fst &fst, bool allow_negative_labels = false) { - const auto start = fst.Start(); - const auto *isyms = fst.InputSymbols(); - const auto *osyms = fst.OutputSymbols(); - const auto ns = CountStates(fst); - if (start == kNoStateId && ns > 0) { - LOG(ERROR) << "Verify: FST start state ID not set"; - return false; - } else if (start >= ns) { - LOG(ERROR) << "Verify: FST start state ID exceeds number of states"; - return false; - } - for (StateIterator> siter(fst); !siter.Done(); siter.Next()) { - auto state = siter.Value(); - size_t na = 0; - for (ArcIterator> aiter(fst, state); !aiter.Done(); aiter.Next()) { - const auto &arc = aiter.Value(); - if (!allow_negative_labels && arc.ilabel < 0) { - LOG(ERROR) << "Verify: FST input label ID of arc at position " << na - << " of state " << state << " is negative"; - return false; - } else if (isyms && !isyms->Member(arc.ilabel)) { - LOG(ERROR) << "Verify: FST input label ID " << arc.ilabel - << " of arc at position " << na << " of state " << state - << " is missing from input symbol table \"" << isyms->Name() - << "\""; - return false; - } else if (!allow_negative_labels && arc.olabel < 0) { - LOG(ERROR) << "Verify: FST output label ID of arc at position " << na - << " of state " << state << " is negative"; - return false; - } else if (osyms && !osyms->Member(arc.olabel)) { - LOG(ERROR) << "Verify: FST output label ID " << arc.olabel - << " of arc at position " << na << " of state " << state - << " is missing from output symbol table \"" << osyms->Name() - << "\""; - return false; - } else if (!arc.weight.Member()) { - LOG(ERROR) << "Verify: FST weight of arc at position " << na - << " of state " << state << " is invalid"; - return false; - } else if (arc.nextstate < 0) { - LOG(ERROR) << "Verify: FST destination state ID of arc at position " - << na << " of state " << state << " is negative"; - return false; - } else if (arc.nextstate >= ns) { - LOG(ERROR) << "Verify: FST destination state ID of arc at position " - << na << " of state " << state - << " exceeds number of states"; - return false; - } - ++na; - } - if (!fst.Final(state).Member()) { - LOG(ERROR) << "Verify: FST final weight of state " << state - << " is invalid"; - return false; - } - } - const auto fst_props = fst.Properties(kFstProperties, /*test=*/false); - if (fst_props & kError) { - LOG(ERROR) << "Verify: FST error property is set"; - return false; - } - uint64_t known_props; - uint64_t test_props = - internal::ComputeProperties(fst, kFstProperties, &known_props); - if (!internal::CompatProperties(fst_props, test_props)) { - LOG(ERROR) << "Verify: Stored FST properties incorrect " - << "(props1 = stored props, props2 = tested)"; - return false; - } else { - return true; - } -} - -} // namespace fst - -#endif // FST_VERIFY_H_ diff --git a/contrib/fstlib/fst/visit.h b/contrib/fstlib/fst/visit.h deleted file mode 100644 index dd5d7a9..0000000 --- a/contrib/fstlib/fst/visit.h +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Queue-dependent visitation of finite-state transducers. See also dfs-visit.h. - -#ifndef FST_VISIT_H_ -#define FST_VISIT_H_ - -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -// Visitor Interface: class determining actions taken during a visit. If any of -// the boolean member functions return false, the visit is aborted by first -// calling FinishState() on all unfinished (grey) states and then calling -// FinishVisit(). -// -// Note this is more general than the visitor interface in dfs-visit.h but lacks -// some DFS-specific behavior. -// -// template -// class Visitor { -// public: -// using StateId = typename Arc::StateId; -// -// Visitor(T *return_data); -// -// // Invoked before visit. -// void InitVisit(const Fst &fst); -// -// // Invoked when state discovered (2nd arg is visitation root). -// bool InitState(StateId s, StateId root); -// -// // Invoked when arc to white/undiscovered state examined. -// bool WhiteArc(StateId s, const Arc &arc); -// -// // Invoked when arc to grey/unfinished state examined. -// bool GreyArc(StateId s, const Arc &arc); -// -// // Invoked when arc to black/finished state examined. -// bool BlackArc(StateId s, const Arc &arc); -// -// // Invoked when state finished. -// void FinishState(StateId s); -// -// // Invoked after visit. -// void FinishVisit(); -// }; - -// Performs queue-dependent visitation. Visitor class argument determines -// actions and contains any return data. ArcFilter determines arcs that are -// considered. If 'access_only' is true, performs visitation only to states -// accessible from the initial state. -template -void Visit(const FST &fst, Visitor *visitor, Queue *queue, ArcFilter filter, - bool access_only = false) { - using Arc = typename FST::Arc; - using StateId = typename Arc::StateId; - visitor->InitVisit(fst); - const auto start = fst.Start(); - if (start == kNoStateId) { - visitor->FinishVisit(); - return; - } - // An FST's state's visit color. - static constexpr uint8_t kWhiteState = 0x01; // Undiscovered. - static constexpr uint8_t kGreyState = 0x02; // Discovered & unfinished. - static constexpr uint8_t kBlackState = 0x04; // Finished. - // We destroy an iterator as soon as possible and mark it so. - static constexpr uint8_t kArcIterDone = 0x08; - std::vector state_status; - std::vector *> arc_iterator; - MemoryPool> aiter_pool; - // Exact number of states if known, otherwise lower bound. - StateId nstates = fst.NumStatesIfKnown().value_or(start + 1); - const bool expanded = fst.Properties(kExpanded, false); - state_status.resize(nstates, kWhiteState); - arc_iterator.resize(nstates); - StateIterator> siter(fst); - // Continues visit while true. - bool visit = true; - // Iterates over trees in visit forest. - for (auto root = start; visit && root < nstates;) { - visit = visitor->InitState(root, root); - state_status[root] = kGreyState; - queue->Enqueue(root); - while (!queue->Empty()) { - auto state = queue->Head(); - if (state >= state_status.size()) { - nstates = state + 1; - state_status.resize(nstates, kWhiteState); - arc_iterator.resize(nstates); - } - // Creates arc iterator if needed. - if (!arc_iterator[state] && !(state_status[state] & kArcIterDone) && - visit) { - arc_iterator[state] = new (&aiter_pool) ArcIterator(fst, state); - } - // Deletes arc iterator if done. - auto *aiter = arc_iterator[state]; - if ((aiter && aiter->Done()) || !visit) { - Destroy(aiter, &aiter_pool); - arc_iterator[state] = nullptr; - state_status[state] |= kArcIterDone; - } - // Dequeues state and marks black if done. - if (state_status[state] & kArcIterDone) { - queue->Dequeue(); - visitor->FinishState(state); - state_status[state] = kBlackState; - continue; - } - const auto &arc = aiter->Value(); - if (arc.nextstate >= state_status.size()) { - nstates = arc.nextstate + 1; - state_status.resize(nstates, kWhiteState); - arc_iterator.resize(nstates); - } - // Visits respective arc types. - if (filter(arc)) { - // Enqueues destination state and marks grey if white. - if (state_status[arc.nextstate] == kWhiteState) { - visit = visitor->WhiteArc(state, arc); - if (!visit) continue; - visit = visitor->InitState(arc.nextstate, root); - state_status[arc.nextstate] = kGreyState; - queue->Enqueue(arc.nextstate); - } else if (state_status[arc.nextstate] == kBlackState) { - visit = visitor->BlackArc(state, arc); - } else { - visit = visitor->GreyArc(state, arc); - } - } - aiter->Next(); - // Destroys an iterator ASAP for efficiency. - if (aiter->Done()) { - Destroy(aiter, &aiter_pool); - arc_iterator[state] = nullptr; - state_status[state] |= kArcIterDone; - } - } - if (access_only) break; - // Finds next tree root. - for (root = (root == start) ? 0 : root + 1; - root < nstates && state_status[root] != kWhiteState; ++root) { - } - // Check for a state beyond the largest known state. - if (!expanded && root == nstates) { - for (; !siter.Done(); siter.Next()) { - if (siter.Value() == nstates) { - ++nstates; - state_status.push_back(kWhiteState); - arc_iterator.push_back(nullptr); - break; - } - } - } - } - visitor->FinishVisit(); -} - -template -inline void Visit(const Fst &fst, Visitor *visitor, Queue *queue) { - Visit(fst, visitor, queue, AnyArcFilter()); -} - -// Copies input FST to mutable FST following queue order. -template -class CopyVisitor { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - explicit CopyVisitor(MutableFst *ofst) : ifst_(nullptr), ofst_(ofst) {} - - void InitVisit(const Fst &ifst) { - ifst_ = &ifst; - ofst_->DeleteStates(); - ofst_->SetStart(ifst_->Start()); - } - - bool InitState(StateId state, StateId) { - while (ofst_->NumStates() <= state) ofst_->AddState(); - return true; - } - - bool WhiteArc(StateId state, const Arc &arc) { - ofst_->AddArc(state, arc); - return true; - } - - bool GreyArc(StateId state, const Arc &arc) { - ofst_->AddArc(state, arc); - return true; - } - - bool BlackArc(StateId state, const Arc &arc) { - ofst_->AddArc(state, arc); - return true; - } - - void FinishState(StateId state) { - ofst_->SetFinal(state, ifst_->Final(state)); - } - - void FinishVisit() {} - - private: - const Fst *ifst_; - MutableFst *ofst_; -}; - -// Visits input FST up to a state limit following queue order. -template -class PartialVisitor { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - explicit PartialVisitor(StateId maxvisit) - : fst_(nullptr), maxvisit_(maxvisit) {} - - void InitVisit(const Fst &ifst) { - fst_ = &ifst; - ninit_ = 0; - nfinish_ = 0; - } - - bool InitState(StateId state, StateId root) { - ++ninit_; - return ninit_ <= maxvisit_; - } - - bool WhiteArc(StateId state, const Arc &arc) { return true; } - - bool GreyArc(StateId state, const Arc &arc) { return true; } - - bool BlackArc(StateId state, const Arc &arc) { return true; } - - void FinishState(StateId state) { - fst_->Final(state); // Visits super-final arc. - ++nfinish_; - } - - void FinishVisit() {} - - StateId NumInitialized() { return ninit_; } - - StateId NumFinished() { return nfinish_; } - - private: - const Fst *fst_; - StateId maxvisit_; - StateId ninit_; - StateId nfinish_; -}; - -// Copies input FST to mutable FST up to a state limit following queue order. -template -class PartialCopyVisitor : public CopyVisitor { - public: - using Arc = A; - using StateId = typename Arc::StateId; - - using CopyVisitor::WhiteArc; - - PartialCopyVisitor(MutableFst *ofst, StateId maxvisit, - bool copy_grey = true, bool copy_black = true) - : CopyVisitor(ofst), - maxvisit_(maxvisit), - copy_grey_(copy_grey), - copy_black_(copy_black) {} - - void InitVisit(const Fst &ifst) { - CopyVisitor::InitVisit(ifst); - ninit_ = 0; - nfinish_ = 0; - } - - bool InitState(StateId state, StateId root) { - CopyVisitor::InitState(state, root); - ++ninit_; - return ninit_ <= maxvisit_; - } - - bool GreyArc(StateId state, const Arc &arc) { - if (copy_grey_) return CopyVisitor::GreyArc(state, arc); - return true; - } - - bool BlackArc(StateId state, const Arc &arc) { - if (copy_black_) return CopyVisitor::BlackArc(state, arc); - return true; - } - - void FinishState(StateId state) { - CopyVisitor::FinishState(state); - ++nfinish_; - } - - void FinishVisit() {} - - StateId NumInitialized() { return ninit_; } - - StateId NumFinished() { return nfinish_; } - - private: - StateId maxvisit_; - StateId ninit_; - StateId nfinish_; - const bool copy_grey_; - const bool copy_black_; -}; - -} // namespace fst - -#endif // FST_VISIT_H_ diff --git a/contrib/fstlib/fst/weight.h b/contrib/fstlib/fst/weight.h deleted file mode 100644 index 0159f95..0000000 --- a/contrib/fstlib/fst/weight.h +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// General weight set and associated semiring operation definitions. - -#ifndef FST_WEIGHT_H_ -#define FST_WEIGHT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -DECLARE_string(fst_weight_parentheses); -DECLARE_string(fst_weight_separator); - -namespace fst { - -// A semiring is specified by two binary operations Plus and Times and two -// designated elements Zero and One with the following properties: -// -// Plus: associative, commutative, and has Zero as its identity. -// -// Times: associative and has identity One, distributes w.r.t. Plus, and -// has Zero as an annihilator: -// Times(Zero(), a) == Times(a, Zero()) = Zero(). -// -// A left semiring distributes on the left; a right semiring is similarly -// defined. -// -// A Weight class must have binary functions Plus and Times and static member -// functions Zero() and One() and these must form (at least) a left or right -// semiring. -// -// In addition, the following should be defined for a Weight: -// -// Member: predicate on set membership. -// -// NoWeight: static member function that returns an element that is -// not a set member; used to signal an error. -// -// >>: reads textual representation of a weight. -// -// <<: prints textual representation of a weight. -// -// Read(istream &istrm): reads binary representation of a weight. -// -// Write(ostream &ostrm): writes binary representation of a weight. -// -// Hash: maps weight to size_t. -// -// ApproxEqual: approximate equality (for inexact weights) -// -// Quantize: quantizes w.r.t delta (for inexact weights) -// -// Divide: -// - In a left semiring, for all a, b, b', c: -// if Times(a, b) = c, Divide(c, a, DIVIDE_LEFT) = b' and b'.Member(), -// then Times(a, b') = c. -// - In a right semiring, for all a, a', b, c: -// if Times(a, b) = c, Divide(c, b, DIVIDE_RIGHT) = a' and a'.Member(), -// then Times(a', b) = c. -// - In a commutative semiring, -// * for all a, c: -// Divide(c, a, DIVIDE_ANY) = Divide(c, a, DIVIDE_LEFT) -// = Divide(c, a, DIVIDE_RIGHT) -// * for all a, b, b', c: -// if Times(a, b) = c, Divide(c, a, DIVIDE_ANY) = b' and b'.Member(), -// then Times(a, b') = c -// - In the case where there exist no b such that c = Times(a, b), the -// return value of Divide(c, a, DIVIDE_LEFT) is unspecified. Returning -// Weight::NoWeight() is recommemded but not required in order to -// allow the most efficient implementation. -// - All algorithms in this library only call Divide(c, a) when it is -// guaranteed that there exists a b such that c = Times(a, b). -// -// ReverseWeight: the type of the corresponding reverse weight. -// -// Typically the same type as Weight for a (both left and right) semiring. -// For the left string semiring, it is the right string semiring. -// -// Reverse: a mapping from Weight to ReverseWeight s.t. -// -// --> Reverse(Reverse(a)) = a -// --> Reverse(Plus(a, b)) = Plus(Reverse(a), Reverse(b)) -// --> Reverse(Times(a, b)) = Times(Reverse(b), Reverse(a)) -// Typically the identity mapping in a (both left and right) semiring. -// In the left string semiring, it maps to the reverse string in the right -// string semiring. -// -// Properties: specifies additional properties that hold: -// LeftSemiring: indicates weights form a left semiring. -// RightSemiring: indicates weights form a right semiring. -// Commutative: for all a, b: Times(a,b) == Times(b, a) -// Idempotent: for all a: Plus(a, a) == a. -// Path: for all a, b: Plus(a, b) == a or Plus(a, b) == b. -// -// User-defined weights and their corresponding operations SHOULD be -// defined in the same namespace, but SHOULD NOT defined in the fst -// namespace. Defining them in fst would make the user code fragile -// to additions in fst. They will be found in another namespace -// via argument-dependent lookup. - -// CONSTANT DEFINITIONS - -// A representable float near .001. -inline constexpr float kDelta = 1.0F / 1024.0F; - -// For all a, b, c: Times(c, Plus(a, b)) = Plus(Times(c, a), Times(c, b)). -inline constexpr uint64_t kLeftSemiring = 0x0000000000000001ULL; - -// For all a, b, c: Times(Plus(a, b), c) = Plus(Times(a, c), Times(b, c)). -inline constexpr uint64_t kRightSemiring = 0x0000000000000002ULL; - -inline constexpr uint64_t kSemiring = kLeftSemiring | kRightSemiring; - -// For all a, b: Times(a, b) = Times(b, a). -inline constexpr uint64_t kCommutative = 0x0000000000000004ULL; - -// For all a: Plus(a, a) = a. -inline constexpr uint64_t kIdempotent = 0x0000000000000008ULL; - -// For all a, b: Plus(a, b) = a or Plus(a, b) = b. -inline constexpr uint64_t kPath = 0x0000000000000010ULL; - -// For random weight generation: default number of distinct weights. -// This is also used for a few other weight generation defaults. -inline constexpr size_t kNumRandomWeights = 5; - -// Weight property boolean constants needed for SFINAE. - -template -using IsIdempotent = std::bool_constant<(W::Properties() & kIdempotent) != 0>; - -template -using IsPath = std::bool_constant<(W::Properties() & kPath) != 0>; - -// Determines direction of division. -enum DivideType { - DIVIDE_LEFT, // left division - DIVIDE_RIGHT, // right division - DIVIDE_ANY -}; // division in a commutative semiring - -// NATURAL ORDER -// -// By definition: -// -// a <= b iff a + b = a -// -// The natural order is a negative partial order iff the semiring is -// idempotent. It is trivially monotonic for plus. It is left -// (resp. right) monotonic for times iff the semiring is left -// (resp. right) distributive. It is a total order iff the semiring -// has the path property. -// -// For more information, see: -// -// Mohri, M. 2002. Semiring framework and algorithms for shortest-distance -// problems, Journal of Automata, Languages and -// Combinatorics 7(3): 321-350, 2002. -// -// We define the strict version of this order below. - -// Requires W is idempotent. -template -struct NaturalLess { - using Weight = W; - static_assert(IsIdempotent::value, "W must be idempotent."); - - bool operator()(const Weight &w1, const Weight &w2) const { - return w1 != w2 && Plus(w1, w2) == w1; - } -}; - -// Power is the iterated product for arbitrary semirings such that Power(w, 0) -// is One() for the semiring, and Power(w, n) = Times(Power(w, n - 1), w). -template -Weight Power(const Weight &weight, size_t n) { - auto result = Weight::One(); - for (size_t i = 0; i < n; ++i) result = Times(result, weight); - return result; -} - -// Simple default adder class. Specializations might be more complex. -template -class Adder { - public: - Adder() : sum_(Weight::Zero()) {} - - explicit Adder(Weight w) : sum_(std::move(w)) {} - - Weight Add(const Weight &w) { - sum_ = Plus(sum_, w); - return sum_; - } - - Weight Sum() const { return sum_; } - - void Reset(Weight w = Weight::Zero()) { sum_ = std::move(w); } - - private: - Weight sum_; -}; - -// General weight converter: raises error. -template -struct WeightConvert { - W2 operator()(W1 w1) const { - FSTERROR() << "WeightConvert: Can't convert weight from " << W1::Type() - << " to " << W2::Type(); - return W2::NoWeight(); - } -}; - -// Specialized weight converter to self. -template -struct WeightConvert { - constexpr W operator()(W weight) const { return weight; } -}; - -// General random weight generator: raises error. -// -// The standard interface is roughly: -// -// class WeightGenerate { -// public: -// explicit WeightGenerate(uint64_t seed = std::random_device()(), -// bool allow_zero = true, -// ...); -// -// MyWeight operator()() const; -// }; -// -// Many weight generators also take trailing constructor arguments specifying -// the number of random (unique) weights, the length of weights (e.g., for -// string-based weights), etc. with sensible defaults -template -struct WeightGenerate { - W operator()() const { - FSTERROR() << "WeightGenerate: No random generator for " << W::Type(); - return W::NoWeight(); - } -}; - -namespace internal { - -class CompositeWeightIO { - public: - CompositeWeightIO(); - CompositeWeightIO(char separator, std::pair parentheses); - - std::pair parentheses() const { - return {open_paren_, close_paren_}; - } - char separator() const { return separator_; } - - bool error() const { return error_; } - - protected: - const char separator_; - const char open_paren_; - const char close_paren_; - - private: - bool error_; -}; - -} // namespace internal - -// Helper class for writing textual composite weights. -class CompositeWeightWriter : public internal::CompositeWeightIO { - public: - // Uses configuration from flags (FST_FLAGS_fst_weight_separator, - // FST_FLAGS_fst_weight_parentheses). - explicit CompositeWeightWriter(std::ostream &ostrm); - - // parentheses defines the opening and closing parenthesis characters. - // Set parentheses = {0, 0} to disable writing parenthesis. - CompositeWeightWriter(std::ostream &ostrm, char separator, - std::pair parentheses); - - CompositeWeightWriter(const CompositeWeightWriter &) = delete; - CompositeWeightWriter &operator=(const CompositeWeightWriter &) = delete; - - // Writes open parenthesis to a stream if option selected. - void WriteBegin(); - - // Writes element to a stream. - template - void WriteElement(const T &comp) { - if (i_++ > 0) ostrm_ << separator_; - ostrm_ << comp; - } - - // Writes close parenthesis to a stream if option selected. - void WriteEnd(); - - private: - std::ostream &ostrm_; - int i_ = 0; // Element position. -}; - -// Helper class for reading textual composite weights. Elements are separated by -// a separator character. There must be at least one element per textual -// representation. Parentheses characters should be set if the composite -// weights themselves contain composite weights to ensure proper parsing. -class CompositeWeightReader : public internal::CompositeWeightIO { - public: - // Uses configuration from flags (FST_FLAGS_fst_weight_separator, - // FST_FLAGS_fst_weight_parentheses). - explicit CompositeWeightReader(std::istream &istrm); - - // parentheses defines the opening and closing parenthesis characters. - // Set parentheses = {0, 0} to disable reading parenthesis. - CompositeWeightReader(std::istream &istrm, char separator, - std::pair parentheses); - - CompositeWeightReader(const CompositeWeightReader &) = delete; - CompositeWeightReader &operator=(const CompositeWeightReader &) = delete; - - // Reads open parenthesis from a stream if option selected. - void ReadBegin(); - - // Reads element from a stream. The second argument, when true, indicates that - // this will be the last element (allowing more forgiving formatting of the - // last element). Returns false when last element is read. - template - bool ReadElement(T *comp, bool last = false); - - // Finalizes reading. - void ReadEnd(); - - private: - std::istream &istrm_; // Input stream. - int c_ = 0; // Last character read, or EOF. - int depth_ = 0; // Weight parentheses depth. -}; - -template -inline bool CompositeWeightReader::ReadElement(T *comp, bool last) { - std::string s; - const bool has_parens = open_paren_ != 0; - while ((c_ != std::istream::traits_type::eof()) && !std::isspace(c_) && - (c_ != separator_ || depth_ > 1 || last) && - (c_ != close_paren_ || depth_ != 1)) { - s += c_; - // If parentheses encountered before separator, they must be matched. - if (has_parens && c_ == open_paren_) { - ++depth_; - } else if (has_parens && c_ == close_paren_) { - // Failure on unmatched parentheses. - if (depth_ == 0) { - FSTERROR() << "CompositeWeightReader: Unmatched close paren: " - << "Is the fst_weight_parentheses flag set correctly?"; - istrm_.clear(std::ios::badbit); - return false; - } - --depth_; - } - c_ = istrm_.get(); - } - if (s.empty()) { - FSTERROR() << "CompositeWeightReader: Empty element: " - << "Is the fst_weight_parentheses flag set correctly?"; - istrm_.clear(std::ios::badbit); - return false; - } - std::istringstream istrm(s); - istrm >> *comp; - // Skips separator/close parenthesis. - if (c_ != std::istream::traits_type::eof() && !std::isspace(c_)) { - c_ = istrm_.get(); - } - const bool is_eof = c_ == std::istream::traits_type::eof(); - // Clears fail bit if just EOF. - if (is_eof && !istrm_.bad()) istrm_.clear(std::ios::eofbit); - return !is_eof && !std::isspace(c_); -} - -} // namespace fst - -#endif // FST_WEIGHT_H_ diff --git a/contrib/fstlib/fst/windows_defs.inc b/contrib/fstlib/fst/windows_defs.inc deleted file mode 100644 index b7efa73..0000000 --- a/contrib/fstlib/fst/windows_defs.inc +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// Aggregator file for common things that need to be defined when building -// for Windows. - -#ifdef _WIN32 -#include -using ssize_t = SSIZE_T; -#endif diff --git a/contrib/fstlib/mapped-file.cc b/contrib/fstlib/mapped-file.cc deleted file mode 100644 index 2e9fdbd..0000000 --- a/contrib/fstlib/mapped-file.cc +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// - -#include - -#include - -#include -#include - -#ifdef _WIN32 -#include // for _get_osfhandle, _open -#include // for CreateFileMapping, UnmapViewOfFile -#include -#else -#include -#include -#endif // _WIN32 - -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace fst { - -#ifdef _WIN32 -namespace { -static constexpr DWORD DWORD_MAX = std::numeric_limits::max(); -} // namespace -#endif // _WIN32 - -MappedFile::MappedFile(const MemoryRegion ®ion) : region_(region) {} - -MappedFile::~MappedFile() { - if (region_.size != 0) { - if (region_.mmap) { - VLOG(2) << "munmap'ed " << region_.size << " bytes at " << region_.mmap; -#ifdef _WIN32 - if (UnmapViewOfFile(region_.mmap) != 0) { - LOG(ERROR) << "Failed to unmap region: " << GetLastError(); - } - CloseHandle(region_.file_mapping); -#else - if (munmap(region_.mmap, region_.size) != 0) { - LOG(ERROR) << "Failed to unmap region: " << strerror(errno); - } -#endif - } else { - if (region_.data) { - operator delete(static_cast(region_.data) - region_.offset); - } - } - } -} - -MappedFile * MappedFile::Map(std::istream &istrm, - bool memorymap, - const std::string &source, - size_t size) { - const auto spos = istrm.tellg(); - VLOG(2) << "memorymap: " << (memorymap ? "true" : "false") << " source: \"" - << source << "\"" - << " size: " << size << " offset: " << spos; - if (memorymap && spos >= 0 && spos % kArchAlignment == 0) { - const size_t pos = static_cast(spos); -#ifdef _WIN32 - const int fd = _open(source.c_str(), _O_RDONLY); -#else - const int fd = open(source.c_str(), O_RDONLY); -#endif - if (fd != -1) { - std::unique_ptr mmf(MapFromFileDescriptor(fd, pos, size)); - if (close(fd) == 0 && mmf != nullptr) { - istrm.seekg(pos + size, std::ios::beg); - if (istrm) { - VLOG(2) << "mmap'ed region of " << size << " at offset " << pos - << " from " << source << " to addr " << mmf->region_.mmap; - return mmf.release(); - } - } else { - LOG(WARNING) << "Mapping of file failed: " << strerror(errno); - } - } - } - - // If all else fails, reads from the file into the allocated buffer. - if (memorymap) { - LOG(WARNING) << "File mapping at offset " << spos << " of file " << source - << " could not be honored, reading instead"; - } - // Reads the file into the buffer in chunks not larger than kMaxReadChunk. - std::unique_ptr mf(Allocate(size)); - auto *buffer = static_cast(mf->mutable_data()); - while (size > 0) { - const auto next_size = std::min(size, kMaxReadChunk); - const auto current_pos = istrm.tellg(); - if (!istrm.read(buffer, next_size)) { - LOG(ERROR) << "Failed to read " << next_size << " bytes at offset " - << current_pos << "from \"" << source << "\""; - return nullptr; - } - size -= next_size; - buffer += next_size; - VLOG(2) << "Read " << next_size << " bytes. " << size << " remaining"; - } - return mf.release(); -} - -MappedFile * MappedFile::MapFromFileDescriptor(int fd, - size_t pos, - size_t size) { -#ifdef _WIN32 - SYSTEM_INFO sysInfo; - GetSystemInfo(&sysInfo); - const DWORD pagesize = sysInfo.dwAllocationGranularity; -#else - const int pagesize = sysconf(_SC_PAGESIZE); -#endif // _WIN32 - - const size_t offset = pos % pagesize; - const size_t offset_pos = pos - offset; - const size_t upsize = size + offset; - -#ifdef _WIN32 - if (fd == -1) { - LOG(ERROR) << "Invalid file descriptor fd=" << fd; - return nullptr; - } - HANDLE file = reinterpret_cast(_get_osfhandle(fd)); - if (file == INVALID_HANDLE_VALUE) { - LOG(ERROR) << "Invalid file descriptor fd=" << fd; - return nullptr; - } - const DWORD max_size_hi = - sizeof(size_t) > sizeof(DWORD) ? upsize >> (CHAR_BIT * sizeof(DWORD)) : 0; - const DWORD max_size_lo = upsize & DWORD_MAX; - HANDLE file_mapping = CreateFileMappingA(file, nullptr, PAGE_READONLY, - max_size_hi, max_size_lo, nullptr); - if (file_mapping == INVALID_HANDLE_VALUE) { - LOG(ERROR) << "Can't create mapping for fd=" << fd << " size=" << upsize - << ": " << GetLastError(); - return nullptr; - } - - const DWORD offset_pos_hi = - sizeof(size_t) > sizeof(DWORD) ? offset_pos >> (CHAR_BIT * sizeof(DWORD)) - : 0; - const DWORD offset_pos_lo = offset_pos & DWORD_MAX; - void *map = MapViewOfFile(file_mapping, FILE_MAP_READ, - offset_pos_hi, offset_pos_lo, upsize); - if (!map) { - LOG(ERROR) << "mmap failed for fd=" << fd << " size=" << upsize - << " offset=" << offset_pos << ": " << GetLastError(); - CloseHandle(file_mapping); - return nullptr; - } -#else - void *map = mmap(nullptr, upsize, PROT_READ, MAP_SHARED, fd, offset_pos); - if (map == MAP_FAILED) { - LOG(ERROR) << "mmap failed for fd=" << fd << " size=" << upsize - << " offset=" << offset_pos; - return nullptr; - } -#endif - MemoryRegion region; - region.mmap = map; - region.size = upsize; - region.data = static_cast(static_cast(map) + offset); - region.offset = offset; -#ifdef _WIN32 - region.file_mapping = file_mapping; -#endif // _WIN32 - return new MappedFile(region); -} - -MappedFile *MappedFile::Allocate(size_t size, size_t align) { - MemoryRegion region; - region.data = nullptr; - region.offset = 0; - if (size > 0) { - // TODO(jrosenstock,sorenj): Use std::align() when that is no longer banned. - // Use std::aligned_alloc() when C++17 is allowed. - char *buffer = static_cast(operator new(size + align)); - uintptr_t address = reinterpret_cast(buffer); - region.offset = align - (address % align); - region.data = buffer + region.offset; - } - region.mmap = nullptr; - region.size = size; - return new MappedFile(region); -} - -MappedFile *MappedFile::Borrow(void *data) { - MemoryRegion region; - region.data = data; - region.mmap = data; - region.size = 0; - region.offset = 0; - return new MappedFile(region); -} - -} // namespace fst diff --git a/contrib/fstlib/properties.cc b/contrib/fstlib/properties.cc deleted file mode 100644 index 33b65ae..0000000 --- a/contrib/fstlib/properties.cc +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Functions for updating property bits for various FST operations and -// string names of the properties. - -#include - -#include -#include -#include - -#include - -namespace fst { - -// These functions determine the properties associated with the FST result of -// various finite-state operations. The property arguments correspond to the -// operation's FST arguments. The properties returned assume the operation -// modifies its first argument. Bitwise-and this result with kCopyProperties for -// the case when a new (possibly delayed) FST is instead constructed. - -// Properties for a concatenatively-closed FST. -uint64_t ClosureProperties(uint64_t inprops, bool, bool delayed) { - auto outprops = (kError | kAcceptor | kUnweighted | kAccessible) & inprops; - if (inprops & kUnweighted) outprops |= kUnweightedCycles; - if (!delayed) { - outprops |= - (kExpanded | kMutable | kCoAccessible | kNotTopSorted | kNotString) & - inprops; - } - if (!delayed || inprops & kAccessible) { - outprops |= (kNotAcceptor | kNonIDeterministic | kNonODeterministic | - kNotILabelSorted | kNotOLabelSorted | kWeighted | - kWeightedCycles | kNotAccessible | kNotCoAccessible) & - inprops; - if ((inprops & kWeighted) && (inprops & kAccessible) && - (inprops & kCoAccessible)) { - outprops |= kWeightedCycles; - } - } - return outprops; -} - -// Properties for a complemented FST. -uint64_t ComplementProperties(uint64_t inprops) { - auto outprops = kAcceptor | kUnweighted | kUnweightedCycles | kNoEpsilons | - kNoIEpsilons | kNoOEpsilons | kIDeterministic | - kODeterministic | kAccessible; - outprops |= - (kError | kILabelSorted | kOLabelSorted | kInitialCyclic) & inprops; - if (inprops & kAccessible) { - outprops |= kNotILabelSorted | kNotOLabelSorted | kCyclic; - } - return outprops; -} - -// Properties for a composed FST. -uint64_t ComposeProperties(uint64_t inprops1, uint64_t inprops2) { - auto outprops = kError & (inprops1 | inprops2); - if (inprops1 & kAcceptor && inprops2 & kAcceptor) { - outprops |= kAcceptor | kAccessible; - outprops |= (kNoEpsilons | kNoIEpsilons | kNoOEpsilons | kAcyclic | - kInitialAcyclic) & - inprops1 & inprops2; - if (kNoIEpsilons & inprops1 & inprops2) { - outprops |= (kIDeterministic | kODeterministic) & inprops1 & inprops2; - } - } else { - outprops |= kAccessible; - outprops |= (kAcceptor | kNoIEpsilons | kAcyclic | kInitialAcyclic) & - inprops1 & inprops2; - if (kNoIEpsilons & inprops1 & inprops2) { - outprops |= kIDeterministic & inprops1 & inprops2; - } - } - return outprops; -} - -// Properties for a concatenated FST. -uint64_t ConcatProperties(uint64_t inprops1, uint64_t inprops2, bool delayed) { - auto outprops = (kAcceptor | kUnweighted | kUnweightedCycles | kAcyclic) & - inprops1 & inprops2; - outprops |= kError & (inprops1 | inprops2); - const bool empty1 = delayed; // Can the first FST be the empty machine? - const bool empty2 = delayed; // Can the second FST be the empty machine? - if (!delayed) { - outprops |= (kExpanded | kMutable | kNotTopSorted | kNotString) & inprops1; - outprops |= (kNotTopSorted | kNotString) & inprops2; - } - if (!empty1) outprops |= (kInitialAcyclic | kInitialCyclic) & inprops1; - if (!delayed || inprops1 & kAccessible) { - outprops |= (kNotAcceptor | kNonIDeterministic | kNonODeterministic | - kEpsilons | kIEpsilons | kOEpsilons | kNotILabelSorted | - kNotOLabelSorted | kWeighted | kWeightedCycles | kCyclic | - kNotAccessible | kNotCoAccessible) & - inprops1; - } - if ((inprops1 & (kAccessible | kCoAccessible)) == - (kAccessible | kCoAccessible) && - !empty1) { - outprops |= kAccessible & inprops2; - if (!empty2) outprops |= kCoAccessible & inprops2; - if (!delayed || inprops2 & kAccessible) { - outprops |= (kNotAcceptor | kNonIDeterministic | kNonODeterministic | - kEpsilons | kIEpsilons | kOEpsilons | kNotILabelSorted | - kNotOLabelSorted | kWeighted | kWeightedCycles | kCyclic | - kNotAccessible | kNotCoAccessible) & - inprops2; - } - } - return outprops; -} - -// Properties for a determinized FST. -uint64_t DeterminizeProperties(uint64_t inprops, bool has_subsequential_label, - bool distinct_psubsequential_labels) { - auto outprops = kAccessible; - if ((kAcceptor & inprops) || - ((kNoIEpsilons & inprops) && distinct_psubsequential_labels) || - (has_subsequential_label && distinct_psubsequential_labels)) { - outprops |= kIDeterministic; - } - outprops |= (kError | kAcceptor | kAcyclic | kInitialAcyclic | kCoAccessible | - kString) & - inprops; - if ((inprops & kNoIEpsilons) && distinct_psubsequential_labels) { - outprops |= kNoEpsilons & inprops; - } - if (inprops & kAccessible) { - outprops |= (kIEpsilons | kOEpsilons | kCyclic) & inprops; - } - if (inprops & kAcceptor) outprops |= (kNoIEpsilons | kNoOEpsilons) & inprops; - if ((inprops & kNoIEpsilons) && has_subsequential_label) { - outprops |= kNoIEpsilons; - } - return outprops; -} - -// Properties for factored weight FST. -uint64_t FactorWeightProperties(uint64_t inprops) { - auto outprops = (kExpanded | kMutable | kError | kAcceptor | kAcyclic | - kAccessible | kCoAccessible) & - inprops; - if (inprops & kAccessible) { - outprops |= (kNotAcceptor | kNonIDeterministic | kNonODeterministic | - kEpsilons | kIEpsilons | kOEpsilons | kCyclic | - kNotILabelSorted | kNotOLabelSorted) & - inprops; - } - return outprops; -} - -// Properties for an inverted FST. -uint64_t InvertProperties(uint64_t inprops) { - auto outprops = (kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | - kEpsilons | kNoEpsilons | kWeighted | kUnweighted | - kWeightedCycles | kUnweightedCycles | kCyclic | kAcyclic | - kInitialCyclic | kInitialAcyclic | kTopSorted | - kNotTopSorted | kAccessible | kNotAccessible | - kCoAccessible | kNotCoAccessible | kString | kNotString) & - inprops; - if (kIDeterministic & inprops) outprops |= kODeterministic; - if (kNonIDeterministic & inprops) outprops |= kNonODeterministic; - if (kODeterministic & inprops) outprops |= kIDeterministic; - if (kNonODeterministic & inprops) outprops |= kNonIDeterministic; - - if (kIEpsilons & inprops) outprops |= kOEpsilons; - if (kNoIEpsilons & inprops) outprops |= kNoOEpsilons; - if (kOEpsilons & inprops) outprops |= kIEpsilons; - if (kNoOEpsilons & inprops) outprops |= kNoIEpsilons; - - if (kILabelSorted & inprops) outprops |= kOLabelSorted; - if (kNotILabelSorted & inprops) outprops |= kNotOLabelSorted; - if (kOLabelSorted & inprops) outprops |= kILabelSorted; - if (kNotOLabelSorted & inprops) outprops |= kNotILabelSorted; - return outprops; -} - -// Properties for a projected FST. -uint64_t ProjectProperties(uint64_t inprops, bool project_input) { - auto outprops = kAcceptor; - outprops |= (kExpanded | kMutable | kError | kWeighted | kUnweighted | - kWeightedCycles | kUnweightedCycles | kCyclic | kAcyclic | - kInitialCyclic | kInitialAcyclic | kTopSorted | kNotTopSorted | - kAccessible | kNotAccessible | kCoAccessible | kNotCoAccessible | - kString | kNotString) & - inprops; - if (project_input) { - outprops |= (kIDeterministic | kNonIDeterministic | kIEpsilons | - kNoIEpsilons | kILabelSorted | kNotILabelSorted) & - inprops; - - if (kIDeterministic & inprops) outprops |= kODeterministic; - if (kNonIDeterministic & inprops) outprops |= kNonODeterministic; - - if (kIEpsilons & inprops) outprops |= kOEpsilons | kEpsilons; - if (kNoIEpsilons & inprops) outprops |= kNoOEpsilons | kNoEpsilons; - - if (kILabelSorted & inprops) outprops |= kOLabelSorted; - if (kNotILabelSorted & inprops) outprops |= kNotOLabelSorted; - } else { - outprops |= (kODeterministic | kNonODeterministic | kOEpsilons | - kNoOEpsilons | kOLabelSorted | kNotOLabelSorted) & - inprops; - - if (kODeterministic & inprops) outprops |= kIDeterministic; - if (kNonODeterministic & inprops) outprops |= kNonIDeterministic; - - if (kOEpsilons & inprops) outprops |= kIEpsilons | kEpsilons; - if (kNoOEpsilons & inprops) outprops |= kNoIEpsilons | kNoEpsilons; - - if (kOLabelSorted & inprops) outprops |= kILabelSorted; - if (kNotOLabelSorted & inprops) outprops |= kNotILabelSorted; - } - return outprops; -} - -// Properties for a randgen FST. -uint64_t RandGenProperties(uint64_t inprops, bool weighted) { - auto outprops = kAcyclic | kInitialAcyclic | kAccessible | kUnweightedCycles; - outprops |= inprops & kError; - if (weighted) { - outprops |= kTopSorted; - outprops |= - (kAcceptor | kNoEpsilons | kNoIEpsilons | kNoOEpsilons | - kIDeterministic | kODeterministic | kILabelSorted | kOLabelSorted) & - inprops; - } else { - outprops |= kUnweighted; - outprops |= (kAcceptor | kILabelSorted | kOLabelSorted) & inprops; - } - return outprops; -} - -// Properties for a replace FST. -uint64_t ReplaceProperties(const std::vector &inprops, size_t root, - bool epsilon_on_call, bool epsilon_on_return, - bool out_epsilon_on_call, bool out_epsilon_on_return, - bool replace_transducer, bool no_empty_fsts, - bool all_ilabel_sorted, bool all_olabel_sorted, - bool all_negative_or_dense) { - if (inprops.empty()) return kNullProperties; - uint64_t outprops = 0; - for (auto inprop : inprops) outprops |= kError & inprop; - uint64_t access_props = no_empty_fsts ? kAccessible | kCoAccessible : 0; - for (auto inprop : inprops) { - access_props &= (inprop & (kAccessible | kCoAccessible)); - } - if (access_props == (kAccessible | kCoAccessible)) { - outprops |= access_props; - if (inprops[root] & kInitialCyclic) outprops |= kInitialCyclic; - uint64_t props = 0; - bool string = true; - for (auto inprop : inprops) { - if (replace_transducer) props |= kNotAcceptor & inprop; - props |= (kNonIDeterministic | kNonODeterministic | kEpsilons | - kIEpsilons | kOEpsilons | kWeighted | kWeightedCycles | - kCyclic | kNotTopSorted | kNotString) & - inprop; - if (!(inprop & kString)) string = false; - } - outprops |= props; - if (string) outprops |= kString; - } - bool acceptor = !replace_transducer; - bool ideterministic = !epsilon_on_call && epsilon_on_return; - bool no_iepsilons = !epsilon_on_call && !epsilon_on_return; - bool acyclic = true; - bool unweighted = true; - for (size_t i = 0; i < inprops.size(); ++i) { - if (!(inprops[i] & kAcceptor)) acceptor = false; - if (!(inprops[i] & kIDeterministic)) ideterministic = false; - if (!(inprops[i] & kNoIEpsilons)) no_iepsilons = false; - if (!(inprops[i] & kAcyclic)) acyclic = false; - if (!(inprops[i] & kUnweighted)) unweighted = false; - if (i != root && !(inprops[i] & kNoIEpsilons)) ideterministic = false; - } - if (acceptor) outprops |= kAcceptor; - if (ideterministic) outprops |= kIDeterministic; - if (no_iepsilons) outprops |= kNoIEpsilons; - if (acyclic) outprops |= kAcyclic; - if (unweighted) outprops |= kUnweighted; - if (inprops[root] & kInitialAcyclic) outprops |= kInitialAcyclic; - // We assume that all terminals are positive. The resulting ReplaceFst is - // known to be kILabelSorted when: (1) all sub-FSTs are kILabelSorted, (2) the - // input label of the return arc is epsilon, and (3) one of the 3 following - // conditions is satisfied: - // - // 1. the input label of the call arc is not epsilon - // 2. all non-terminals are negative, or - // 3. all non-terninals are positive and form a dense range containing 1. - if (all_ilabel_sorted && epsilon_on_return && - (!epsilon_on_call || all_negative_or_dense)) { - outprops |= kILabelSorted; - } - // Similarly, the resulting ReplaceFst is known to be kOLabelSorted when: (1) - // all sub-FSTs are kOLabelSorted, (2) the output label of the return arc is - // epsilon, and (3) one of the 3 following conditions is satisfied: - // - // 1. the output label of the call arc is not epsilon - // 2. all non-terminals are negative, or - // 3. all non-terninals are positive and form a dense range containing 1. - if (all_olabel_sorted && out_epsilon_on_return && - (!out_epsilon_on_call || all_negative_or_dense)) { - outprops |= kOLabelSorted; - } - return outprops; -} - -// Properties for a relabeled FST. -uint64_t RelabelProperties(uint64_t inprops) { - static constexpr auto outprops = - kExpanded | kMutable | kError | kWeighted | kUnweighted | - kWeightedCycles | kUnweightedCycles | kCyclic | kAcyclic | - kInitialCyclic | kInitialAcyclic | kTopSorted | kNotTopSorted | - kAccessible | kNotAccessible | kCoAccessible | kNotCoAccessible | - kString | kNotString; - return outprops & inprops; -} - -// Properties for a reversed FST (the superinitial state limits this set). -uint64_t ReverseProperties(uint64_t inprops, bool has_superinitial) { - auto outprops = (kExpanded | kMutable | kError | kAcceptor | kNotAcceptor | - kEpsilons | kIEpsilons | kOEpsilons | kUnweighted | kCyclic | - kAcyclic | kWeightedCycles | kUnweightedCycles) & - inprops; - if (has_superinitial) outprops |= kWeighted & inprops; - return outprops; -} - -// Properties for re-weighted FST. -uint64_t ReweightProperties(uint64_t inprops, bool added_start_epsilon) { - auto outprops = inprops & kWeightInvariantProperties; - outprops = outprops & ~kCoAccessible; - if (added_start_epsilon) { - outprops &= ~(kNoEpsilons | kNoIEpsilons | kNoOEpsilons | kInitialCyclic); - outprops |= kEpsilons | kIEpsilons | kOEpsilons | kInitialAcyclic; - } - return outprops; -} - -// Properties for an epsilon-removed FST. -uint64_t RmEpsilonProperties(uint64_t inprops, bool delayed) { - auto outprops = kNoEpsilons; - outprops |= (kError | kAcceptor | kAcyclic | kInitialAcyclic) & inprops; - if (inprops & kAcceptor) outprops |= kNoIEpsilons | kNoOEpsilons; - if (!delayed) { - outprops |= kExpanded | kMutable; - outprops |= kTopSorted & inprops; - } - if (!delayed || inprops & kAccessible) outprops |= kNotAcceptor & inprops; - return outprops; -} - -// Properties for shortest path. This function computes how the properties of -// the output of shortest path need to be updated, given that 'props' is already -// known. -uint64_t ShortestPathProperties(uint64_t props, bool tree) { - auto outprops = - props | kAcyclic | kInitialAcyclic | kAccessible | kUnweightedCycles; - if (!tree) outprops |= kCoAccessible; - return outprops; -} - -// Properties for a synchronized FST. -uint64_t SynchronizeProperties(uint64_t inprops) { - auto outprops = (kError | kAcceptor | kAcyclic | kAccessible | kCoAccessible | - kUnweighted | kUnweightedCycles) & - inprops; - if (inprops & kAccessible) { - outprops |= - (kCyclic | kNotCoAccessible | kWeighted | kWeightedCycles) & inprops; - } - return outprops; -} - -// Properties for a unioned FST. -uint64_t UnionProperties(uint64_t inprops1, uint64_t inprops2, bool delayed) { - auto outprops = - (kAcceptor | kUnweighted | kUnweightedCycles | kAcyclic | kAccessible) & - inprops1 & inprops2; - outprops |= kError & (inprops1 | inprops2); - outprops |= kInitialAcyclic; - bool empty1 = delayed; // Can the first FST be the empty machine? - bool empty2 = delayed; // Can the second FST be the empty machine? - if (!delayed) { - outprops |= (kExpanded | kMutable | kNotTopSorted) & inprops1; - outprops |= kNotTopSorted & inprops2; - } - if (!empty1 && !empty2) { - outprops |= kEpsilons | kIEpsilons | kOEpsilons; - outprops |= kCoAccessible & inprops1 & inprops2; - } - // Note kNotCoAccessible does not hold because of kInitialAcyclic option. - if (!delayed || inprops1 & kAccessible) { - outprops |= - (kNotAcceptor | kNonIDeterministic | kNonODeterministic | kEpsilons | - kIEpsilons | kOEpsilons | kNotILabelSorted | kNotOLabelSorted | - kWeighted | kWeightedCycles | kCyclic | kNotAccessible) & - inprops1; - } - if (!delayed || inprops2 & kAccessible) { - outprops |= (kNotAcceptor | kNonIDeterministic | kNonODeterministic | - kEpsilons | kIEpsilons | kOEpsilons | kNotILabelSorted | - kNotOLabelSorted | kWeighted | kWeightedCycles | kCyclic | - kNotAccessible | kNotCoAccessible) & - inprops2; - } - return outprops; -} - -namespace internal { -// Property string names (indexed by bit position). -const std::string_view PropertyNames[] = { - // Binary. - "expanded", "mutable", "error", "", "", "", "", "", "", "", "", "", "", "", - "", "", - // Ternary. - "acceptor", "not acceptor", "input deterministic", - "non input deterministic", "output deterministic", - "non output deterministic", "input/output epsilons", - "no input/output epsilons", "input epsilons", "no input epsilons", - "output epsilons", "no output epsilons", "input label sorted", - "not input label sorted", "output label sorted", "not output label sorted", - "weighted", "unweighted", "cyclic", "acyclic", "cyclic at initial state", - "acyclic at initial state", "top sorted", "not top sorted", "accessible", - "not accessible", "coaccessible", "not coaccessible", "string", - "not string", "weighted cycles", "unweighted cycles"}; -} // namespace internal -} // namespace fst diff --git a/contrib/fstlib/symbol-table-ops.cc b/contrib/fstlib/symbol-table-ops.cc deleted file mode 100644 index db12e23..0000000 --- a/contrib/fstlib/symbol-table-ops.cc +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace fst { - -SymbolTable *MergeSymbolTable(const SymbolTable &left, const SymbolTable &right, - bool *right_relabel_output) { - // MergeSymbolTable detects several special cases It will return a reference - // copied version of SymbolTable of left or right if either symbol table is - // a superset of the other. - std::unique_ptr merged( - new SymbolTable("merge_" + left.Name() + "_" + right.Name())); - // Copies everything from the left symbol table. - bool left_has_all = true; - bool right_has_all = true; - bool relabel = false; - for (const auto &litem : left) { - merged->AddSymbol(litem.Symbol(), litem.Label()); - if (right_has_all) { - int64_t key = right.Find(litem.Symbol()); - if (key == kNoSymbol) { - right_has_all = false; - } else if (!relabel && key != litem.Label()) { - relabel = true; - } - } - } - if (right_has_all) { - if (right_relabel_output) *right_relabel_output = relabel; - return right.Copy(); - } - // Adds all symbols we can from right symbol table. - std::vector conflicts; - for (const auto &ritem : right) { - int64_t key = merged->Find(ritem.Symbol()); - if (key != -1) { - // Symbol already exists, maybe with different value. - if (key != ritem.Label()) relabel = true; - continue; - } - // Symbol doesn't exist from left. - left_has_all = false; - if (!merged->Find(ritem.Label()).empty()) { - // We can't add this where we want to, add it later, in order. - conflicts.push_back(ritem.Symbol()); - continue; - } - // There is a hole and we can add this symbol with its ID. - merged->AddSymbol(ritem.Symbol(), ritem.Label()); - } - if (right_relabel_output) *right_relabel_output = relabel; - if (left_has_all) return left.Copy(); - // Adds all symbols that conflicted, in order. - for (const auto &conflict : conflicts) merged->AddSymbol(conflict); - return merged.release(); -} - -SymbolTable *CompactSymbolTable(const SymbolTable &syms) { - std::map sorted; - for (const auto &stitem : syms) { - sorted[stitem.Label()] = stitem.Symbol(); - } - auto compact = std::make_unique(syms.Name() + "_compact"); - int64_t newkey = 0; - for (const auto &kv : sorted) compact->AddSymbol(kv.second, newkey++); - return compact.release(); -} - -SymbolTable * FstReadSymbols(const std::string &source, - bool input_symbols) { - std::ifstream in(source, std::ios_base::in | std::ios_base::binary); - if (!in) { - LOG(ERROR) << "FstReadSymbols: Can't open file " << source; - return nullptr; - } - FstHeader hdr; - if (!hdr.Read(in, source)) { - LOG(ERROR) << "FstReadSymbols: Couldn't read header from " << source; - return nullptr; - } - if (hdr.GetFlags() & FstHeader::HAS_ISYMBOLS) { - std::unique_ptr isymbols(SymbolTable::Read(in, source)); - if (isymbols == nullptr) { - LOG(ERROR) << "FstReadSymbols: Couldn't read input symbols from " - << source; - return nullptr; - } - if (input_symbols) return isymbols.release(); - } - if (hdr.GetFlags() & FstHeader::HAS_OSYMBOLS) { - std::unique_ptr osymbols(SymbolTable::Read(in, source)); - if (osymbols == nullptr) { - LOG(ERROR) << "FstReadSymbols: Couldn't read output symbols from " - << source; - return nullptr; - } - if (!input_symbols) return osymbols.release(); - } - LOG(ERROR) << "FstReadSymbols: The file " << source - << " doesn't contain the requested symbols"; - return nullptr; -} - -bool AddAuxiliarySymbols(const std::string &prefix, int64_t start_label, - int64_t nlabels, SymbolTable *syms) { - for (int64_t i = 0; i < nlabels; ++i) { - auto index = i + start_label; - if (index != syms->AddSymbol(prefix + std::to_string(i), index)) { - FSTERROR() << "AddAuxiliarySymbols: Symbol table clash"; - return false; - } - } - return true; -} - -} // namespace fst diff --git a/contrib/fstlib/symbol-table.cc b/contrib/fstlib/symbol-table.cc deleted file mode 100644 index 93dc753..0000000 --- a/contrib/fstlib/symbol-table.cc +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// Classes to provide symbol-to-integer and integer-to-symbol mappings. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -DEFINE_bool(fst_compat_symbols, true, - "Require symbol tables to match when appropriate"); -DEFINE_string(fst_field_separator, "\t ", - "Set of characters used as a separator between printed fields"); - -namespace fst { -namespace internal { - -// Identifies stream data as a symbol table (and its endianity). -static constexpr int32_t kSymbolTableMagicNumber = 2125658996; - -DenseSymbolMap::DenseSymbolMap() - : str_hash_(), - buckets_(1 << 4, kEmptyBucket), - hash_mask_(buckets_.size() - 1) {} - -std::pair DenseSymbolMap::InsertOrFind(std::string_view key) { - static constexpr float kMaxOccupancyRatio = 0.75; // Grows when 75% full. - if (Size() >= kMaxOccupancyRatio * buckets_.size()) { - Rehash(buckets_.size() * 2); - } - size_t idx = GetHash(key); - while (buckets_[idx] != kEmptyBucket) { - const auto stored_value = buckets_[idx]; - if (symbols_[stored_value] == key) return {stored_value, false}; - idx = (idx + 1) & hash_mask_; - } - const auto next = Size(); - buckets_[idx] = next; - symbols_.emplace_back(key); - return {next, true}; -} - -int64_t DenseSymbolMap::Find(std::string_view key) const { - size_t idx = str_hash_(key) & hash_mask_; - while (buckets_[idx] != kEmptyBucket) { - const auto stored_value = buckets_[idx]; - if (symbols_[stored_value] == key) return stored_value; - idx = (idx + 1) & hash_mask_; - } - return buckets_[idx]; -} - -void DenseSymbolMap::Rehash(size_t num_buckets) { - buckets_.resize(num_buckets); - hash_mask_ = buckets_.size() - 1; - std::fill(buckets_.begin(), buckets_.end(), kEmptyBucket); - for (size_t i = 0; i < Size(); ++i) { - size_t idx = GetHash(symbols_[i]); - while (buckets_[idx] != kEmptyBucket) { - idx = (idx + 1) & hash_mask_; - } - buckets_[idx] = i; - } -} - -void DenseSymbolMap::RemoveSymbol(size_t idx) { - symbols_.erase(symbols_.begin() + idx); - Rehash(buckets_.size()); -} - -void DenseSymbolMap::ShrinkToFit() { symbols_.shrink_to_fit(); } - -void MutableSymbolTableImpl::AddTable(const SymbolTable &table) { - for (const auto &item : table) { - AddSymbol(item.Symbol()); - } -} - -std::unique_ptr -ConstSymbolTableImpl::Copy() const { - LOG(FATAL) << "ConstSymbolTableImpl can't be copied"; - return nullptr; -} - -int64_t ConstSymbolTableImpl::AddSymbol(std::string_view symbol, int64_t key) { - LOG(FATAL) << "ConstSymbolTableImpl does not support AddSymbol"; - return kNoSymbol; -} - -int64_t ConstSymbolTableImpl::AddSymbol(std::string_view symbol) { - return AddSymbol(symbol, kNoSymbol); -} - -void ConstSymbolTableImpl::RemoveSymbol(int64_t key) { - LOG(FATAL) << "ConstSymbolTableImpl does not support RemoveSymbol"; -} - -void ConstSymbolTableImpl::SetName(std::string_view new_name) { - LOG(FATAL) << "ConstSymbolTableImpl does not support SetName"; -} - -void ConstSymbolTableImpl::AddTable(const SymbolTable &table) { - LOG(FATAL) << "ConstSymbolTableImpl does not support AddTable"; -} - -SymbolTableImpl * SymbolTableImpl::ReadText( - std::istream &strm, std::string_view name, const std::string &sep) { - auto impl = std::make_unique(name); - int64_t nline = 0; - char line[kLineLen]; - const auto separator = sep + "\n"; - while (!strm.getline(line, kLineLen).fail()) { - ++nline; - const std::vector col = - StrSplit(line, ByAnyChar(separator), SkipEmpty()); - if (col.empty()) continue; // Empty line. - if (col.size() != 2) { - LOG(ERROR) << "SymbolTable::ReadText: Bad number of columns (" - << col.size() << "), " - << "file = " << name << ", line = " << nline << ": " << line; - return nullptr; - } - std::string_view symbol = col[0]; - std::string_view value = col[1]; - const auto maybe_key = ParseInt64(value); - if (!maybe_key.has_value() || *maybe_key == kNoSymbol) { - LOG(ERROR) << "SymbolTable::ReadText: Bad label (" << value << "), " - << "file = " << name << ", line = " << nline; - return nullptr; - } - impl->AddSymbol(symbol, *maybe_key); - } - impl->ShrinkToFit(); - return impl.release(); -} - -void SymbolTableImpl::MaybeRecomputeCheckSum() const { - { - ReaderMutexLock check_sum_lock(&check_sum_mutex_); - if (check_sum_finalized_) return; - } - // We'll acquire an exclusive lock to recompute the checksums. - MutexLock check_sum_lock(&check_sum_mutex_); - if (check_sum_finalized_) { // Another thread (coming in around the same time - return; // might have done it already). So we recheck. - } - // Calculates the original label-agnostic checksum. - CheckSummer check_sum; - for (size_t i = 0; i < symbols_.Size(); ++i) { - check_sum.Update(symbols_.GetSymbol(i)); - check_sum.Update(std::string_view{"\0", 1}); - } - check_sum_string_ = check_sum.Digest(); - // Calculates the safer, label-dependent checksum. - CheckSummer labeled_check_sum; - for (int64_t i = 0; i < dense_key_limit_; ++i) { - std::ostringstream line; - line << symbols_.GetSymbol(i) << '\t' << i; - labeled_check_sum.Update(line.str()); - } - using citer = std::map::const_iterator; - for (citer it = key_map_.begin(); it != key_map_.end(); ++it) { - // TODO(tombagby, 2013-11-22) This line maintains a bug that ignores - // negative labels in the checksum that too many tests rely on. - if (it->first < dense_key_limit_) continue; - std::ostringstream line; - line << symbols_.GetSymbol(it->second) << '\t' << it->first; - labeled_check_sum.Update(line.str()); - } - labeled_check_sum_string_ = labeled_check_sum.Digest(); - check_sum_finalized_ = true; -} - -std::string SymbolTableImpl::Find(int64_t key) const { - int64_t idx = key; - if (key < 0 || key >= dense_key_limit_) { - const auto it = key_map_.find(key); - if (it == key_map_.end()) return ""; - idx = it->second; - } - if (idx < 0 || idx >= symbols_.Size()) return ""; - return symbols_.GetSymbol(idx); -} - -int64_t SymbolTableImpl::AddSymbol(std::string_view symbol, int64_t key) { - if (key == kNoSymbol) return key; - if (const auto &[insert_key, inserted] = symbols_.InsertOrFind(symbol); - !inserted) { - const auto key_already = GetNthKey(insert_key); - if (key_already == key) return key; - VLOG(1) << "SymbolTable::AddSymbol: symbol = " << symbol - << " already in symbol_map_ with key = " << key_already - << " but supplied new key = " << key << " (ignoring new key)"; - return key_already; - } - if (key + 1 == static_cast(symbols_.Size()) && - key == dense_key_limit_) { - ++dense_key_limit_; - } else { - idx_key_.push_back(key); - key_map_[key] = symbols_.Size() - 1; - } - if (key >= available_key_) available_key_ = key + 1; - check_sum_finalized_ = false; - return key; -} - -// TODO(rybach): Consider a more efficient implementation which re-uses holes in -// the dense-key range or re-arranges the dense-key range from time to time. -void SymbolTableImpl::RemoveSymbol(const int64_t key) { - auto idx = key; - if (key < 0 || key >= dense_key_limit_) { - auto iter = key_map_.find(key); - if (iter == key_map_.end()) return; - idx = iter->second; - key_map_.erase(iter); - } - if (idx < 0 || idx >= static_cast(symbols_.Size())) return; - symbols_.RemoveSymbol(idx); - // Removed one symbol, all indexes > idx are shifted by -1. - for (auto &k : key_map_) { - if (k.second > idx) --k.second; - } - if (key >= 0 && key < dense_key_limit_) { - // Removal puts a hole in the dense key range. Adjusts range to [0, key). - const auto new_dense_key_limit = key; - for (int64_t i = key + 1; i < dense_key_limit_; ++i) { - key_map_[i] = i - 1; - } - // Moves existing values in idx_key to new place. - idx_key_.resize(symbols_.Size() - new_dense_key_limit); - for (int64_t i = symbols_.Size(); i >= dense_key_limit_; --i) { - idx_key_[i - new_dense_key_limit - 1] = idx_key_[i - dense_key_limit_]; - } - // Adds indexes for previously dense keys. - for (int64_t i = new_dense_key_limit; i < dense_key_limit_ - 1; ++i) { - idx_key_[i - new_dense_key_limit] = i + 1; - } - dense_key_limit_ = new_dense_key_limit; - } else { - // Remove entry for removed index in idx_key. - for (size_t i = idx - dense_key_limit_; i + 1 < idx_key_.size(); ++i) { - idx_key_[i] = idx_key_[i + 1]; - } - idx_key_.pop_back(); - } - if (key == available_key_ - 1) available_key_ = key; -} - -SymbolTableImpl * SymbolTableImpl::Read( - std::istream &strm, std::string_view source) { - int32_t magic_number = 0; - ReadType(strm, &magic_number); - if (strm.fail()) { - LOG(ERROR) << "SymbolTable::Read: Read failed: " << source; - return nullptr; - } - std::string name; - ReadType(strm, &name); - auto impl = std::make_unique(name); - ReadType(strm, &impl->available_key_); - int64_t size; - ReadType(strm, &size); - if (strm.fail()) { - LOG(ERROR) << "SymbolTable::Read: Read failed: " << source; - return nullptr; - } - std::string symbol; - int64_t key; - impl->check_sum_finalized_ = false; - for (int64_t i = 0; i < size; ++i) { - ReadType(strm, &symbol); - ReadType(strm, &key); - if (strm.fail()) { - LOG(ERROR) << "SymbolTable::Read: Read failed: " << source; - return nullptr; - } - impl->AddSymbol(symbol, key); - } - impl->ShrinkToFit(); - return impl.release(); -} - -bool SymbolTableImpl::Write(std::ostream &strm) const { - WriteType(strm, kSymbolTableMagicNumber); - WriteType(strm, name_); - WriteType(strm, available_key_); - const int64_t size = symbols_.Size(); - WriteType(strm, size); - for (int64_t i = 0; i < dense_key_limit_; ++i) { - WriteType(strm, symbols_.GetSymbol(i)); - WriteType(strm, i); - } - for (const auto &p : key_map_) { - WriteType(strm, symbols_.GetSymbol(p.second)); - WriteType(strm, p.first); - } - strm.flush(); - if (strm.fail()) { - LOG(ERROR) << "SymbolTable::Write: Write failed"; - return false; - } - return true; -} - -void SymbolTableImpl::ShrinkToFit() { symbols_.ShrinkToFit(); } - -} // namespace internal - -SymbolTable * SymbolTable::ReadText(const std::string &source, - const std::string &sep) { - std::ifstream strm(source, std::ios_base::in); - if (!strm.good()) { - LOG(ERROR) << "SymbolTable::ReadText: Can't open file: " << source; - return nullptr; - } - return ReadText(strm, source, sep); -} - -bool SymbolTable::Write(const std::string &source) const { - if (!source.empty()) { - std::ofstream strm(source, - std::ios_base::out | std::ios_base::binary); - if (!strm) { - LOG(ERROR) << "SymbolTable::Write: Can't open file: " << source; - return false; - } - if (!Write(strm)) { - LOG(ERROR) << "SymbolTable::Write: Write failed: " << source; - return false; - } - return true; - } else { - return Write(std::cout); - } -} - -bool SymbolTable::WriteText(std::ostream &strm, const std::string &sep) const { - for (const auto &item : *this) { - std::ostringstream line; - line << item.Symbol() << sep[0] << item.Label() << '\n'; - strm.write(line.str().data(), line.str().length()); - } - return true; -} - -bool SymbolTable::WriteText(const std::string &sink, - const std::string &sep) const { - if (!sink.empty()) { - std::ofstream strm(sink); - if (!strm) { - LOG(ERROR) << "SymbolTable::WriteText: Can't open file: " << sink; - return false; - } - if (!WriteText(strm, sep)) { - LOG(ERROR) << "SymbolTable::WriteText: Write failed: " << sink; - return false; - } - return true; - } else { - return WriteText(std::cout, sep); - } -} - -bool CompatSymbols(const SymbolTable *syms1, const SymbolTable *syms2, - bool warning) { - // Flag can explicitly override this check. - if (!FST_FLAGS_fst_compat_symbols) return true; - if (syms1 && syms2 && - (syms1->LabeledCheckSum() != syms2->LabeledCheckSum())) { - if (warning) { - LOG(WARNING) << "CompatSymbols: Symbol table checksums do not match. " - << "Table sizes are " << syms1->NumSymbols() << " and " - << syms2->NumSymbols(); - } - return false; - } else { - return true; - } -} - -void SymbolTableToString(const SymbolTable *table, std::string *result) { - std::ostringstream ostrm; - table->Write(ostrm); - *result = ostrm.str(); -} - -SymbolTable *StringToSymbolTable(const std::string &str) { - std::istringstream istrm(str); - // TODO(jrosenstock): Change to source="string". - return SymbolTable::Read(istrm, /*source=*/""); -} - -} // namespace fst diff --git a/contrib/fstlib/util.cc b/contrib/fstlib/util.cc deleted file mode 100644 index 69e4de2..0000000 --- a/contrib/fstlib/util.cc +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -// See www.openfst.org for extensive documentation on this weighted -// finite-state transducer library. -// -// FST utility definitions. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -// Utility flag definitions - -DEFINE_bool(fst_error_fatal, true, - "FST errors are fatal; o.w. return objects flagged as bad: " - "e.g., FSTs: kError property set, FST weights: not a Member()"); - -namespace fst { - -std::optional ParseInt64(std::string_view s, int base) { - // Portability note: std::from_chars does not play nicely with string_view - // using Microsoft Visual Studio Compiler. The string_view's begin() and end() - // do not return implicit char pointers on this platforms. Using data() - // and size() instead should be more portable. - // - // See: https://stackoverflow.com/questions/61203317/stdfrom-chars-doenst-compile-under-msvc - int64_t n; - if (const auto [p, ec] = - std::from_chars(s.data(), s.data() + s.size(), n, /*base=*/base); - ec != std::errc() || p != (s.data() + s.size())) { - return std::nullopt; - } - return n; -} - -int64_t StrToInt64(std::string_view s, std::string_view source, size_t nline, - bool * error) { - if (error) *error = false; - const std::optional maybe_n = ParseInt64(s); - if (!maybe_n.has_value()) { - FSTERROR() << "StrToInt64: Bad integer = " << s << "\", source = " << source - << ", line = " << nline; - if (error) *error = true; - return 0; - } - return *maybe_n; -} - -void ConvertToLegalCSymbol(std::string *s) { - for (auto it = s->begin(); it != s->end(); ++it) { - if (!isalnum(*it)) { - *it = '_'; - } - } -} - -// Skips over input characters to align to 'align' bytes. Returns false if can't -// align. -bool AlignInput(std::istream &strm, size_t align) { - char c; - for (size_t i = 0; i < align; ++i) { - int64_t pos = strm.tellg(); - if (pos < 0) { - LOG(ERROR) << "AlignInput: Can't determine stream position"; - return false; - } - if (pos % align == 0) break; - strm.read(&c, 1); - } - return true; -} - -// Write null output characters to align to 'align' bytes. Returns false if -// can't align. -bool AlignOutput(std::ostream &strm, size_t align) { - for (size_t i = 0; i < align; ++i) { - int64_t pos = strm.tellp(); - if (pos < 0) { - LOG(ERROR) << "AlignOutput: Can't determine stream position"; - return false; - } - if (pos % align == 0) break; - strm.write("", 1); - } - return true; -} - -int AlignBufferWithOutputStream(std::ostream &strm, - std::ostringstream &buffer, - size_t align) { - const auto strm_pos = strm.tellp(); - if (strm_pos == -1) { - LOG(ERROR) << "Cannot determine stream position"; - return -1; - } - const int stream_offset = strm_pos % align; - for (int i = 0; i < stream_offset; ++i) buffer.write("", 1); - return stream_offset; -} - -} // namespace fst diff --git a/contrib/fstlib/weight.cc b/contrib/fstlib/weight.cc deleted file mode 100644 index 2feccb9..0000000 --- a/contrib/fstlib/weight.cc +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2005-2024 Google LLC -// -// 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. -// -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -DEFINE_string(fst_weight_separator, ",", - "Character separator between printed composite weights; " - "must be a single character"); - -DEFINE_string(fst_weight_parentheses, "", - "Characters enclosing the first weight of a printed composite " - "weight (e.g., pair weight, tuple weight and derived classes) to " - "ensure proper I/O of nested composite weights; " - "must have size 0 (none) or 2 (open and close parenthesis)"); - -namespace fst { - -namespace internal { - -CompositeWeightIO::CompositeWeightIO(char separator, - std::pair parentheses) - : separator_(separator), - open_paren_(parentheses.first), - close_paren_(parentheses.second), - error_(false) { - if ((open_paren_ == 0 || close_paren_ == 0) && open_paren_ != close_paren_) { - FSTERROR() << "Invalid configuration of weight parentheses: " - << static_cast(open_paren_) << " " - << static_cast(close_paren_); - error_ = true; - } -} - -CompositeWeightIO::CompositeWeightIO() - : CompositeWeightIO( - FST_FLAGS_fst_weight_separator.empty() - ? 0 - : FST_FLAGS_fst_weight_separator.front(), - {FST_FLAGS_fst_weight_parentheses.empty() - ? 0 - : FST_FLAGS_fst_weight_parentheses[0], - FST_FLAGS_fst_weight_parentheses.size() < 2 - ? 0 - : FST_FLAGS_fst_weight_parentheses[1]}) { - if (FST_FLAGS_fst_weight_separator.size() != 1) { - FSTERROR() << "CompositeWeight: " - << "FST_FLAGS_fst_weight_separator.size() is not equal to 1"; - error_ = true; - } - if (!FST_FLAGS_fst_weight_parentheses.empty() && - FST_FLAGS_fst_weight_parentheses.size() != 2) { - FSTERROR() << "CompositeWeight: " - << "FST_FLAGS_fst_weight_parentheses.size() is not equal to 2"; - error_ = true; - } -} - -} // namespace internal - -CompositeWeightWriter::CompositeWeightWriter(std::ostream &ostrm) - : ostrm_(ostrm) { - if (error()) ostrm.clear(std::ios::badbit); -} - -CompositeWeightWriter::CompositeWeightWriter(std::ostream &ostrm, - char separator, - std::pair parentheses) - : internal::CompositeWeightIO(separator, parentheses), ostrm_(ostrm) { - if (error()) ostrm_.clear(std::ios::badbit); -} - -void CompositeWeightWriter::WriteBegin() { - if (open_paren_ != 0) { - ostrm_ << open_paren_; - } -} - -void CompositeWeightWriter::WriteEnd() { - if (close_paren_ != 0) { - ostrm_ << close_paren_; - } -} - -CompositeWeightReader::CompositeWeightReader(std::istream &istrm) - : istrm_(istrm) { - if (error()) istrm_.clear(std::ios::badbit); -} - -CompositeWeightReader::CompositeWeightReader(std::istream &istrm, - char separator, - std::pair parentheses) - : internal::CompositeWeightIO(separator, parentheses), istrm_(istrm) { - if (error()) istrm_.clear(std::ios::badbit); -} - -void CompositeWeightReader::ReadBegin() { - do { // Skips whitespace. - c_ = istrm_.get(); - } while (std::isspace(c_)); - if (open_paren_ != 0) { - if (c_ != open_paren_) { - FSTERROR() << "CompositeWeightReader: Open paren missing: " - << "fst_weight_parentheses flag set correcty?"; - istrm_.clear(std::ios::badbit); - return; - } - ++depth_; - c_ = istrm_.get(); - } -} - -void CompositeWeightReader::ReadEnd() { - if (c_ != EOF && !std::isspace(c_)) { - FSTERROR() << "CompositeWeightReader: excess character: '" - << static_cast(c_) - << "': fst_weight_parentheses flag set correcty?"; - istrm_.clear(std::ios::badbit); - } -} - -} // namespace fst diff --git a/contrib/meson.build b/contrib/meson.build index d7cadf7..f8b6ba7 100644 --- a/contrib/meson.build +++ b/contrib/meson.build @@ -10,18 +10,4 @@ librandom_dep = declare_dependency( link_with : librandom ) -fstlib = static_library( - 'fstlib', ['fstlib/compat.cc', 'fstlib/encode.cc', 'fstlib/flags.cc', - 'fstlib/fst-types.cc', 'fstlib/fst.cc', 'fstlib/mapped-file.cc', - 'fstlib/properties.cc', 'fstlib/symbol-table-ops.cc', - 'fstlib/symbol-table.cc', 'fstlib/util.cc', 'fstlib/weight.cc'], - include_directories : include_directories('fstlib'), - override_options : 'warning_level=0' -) - -fstlib_dep = declare_dependency( - include_directories : include_directories('fstlib', is_system : true), - link_with : fstlib -) - cli_dep = declare_dependency(include_directories : include_directories('CLI', is_system : true)) diff --git a/meson_options.txt b/meson_options.txt index 22b1b87..8bdac14 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -1,2 +1,3 @@ option('benchmark', type : 'boolean', value : false, description : 'Build benchmark tests') option('test', type : 'boolean', value : true, description : 'Build unit tests') +option('system_openfst', type : 'feature', value : 'auto', description : 'Use an installed OpenFst, 1.8.4 or later (auto: when one works; otherwise Meson downloads OpenFst 1.8.5)') diff --git a/src/lib/meson.build b/src/lib/meson.build index e72d453..d748669 100644 --- a/src/lib/meson.build +++ b/src/lib/meson.build @@ -38,7 +38,7 @@ libcoati_sources = files([ 'version.cc' ]) -libcoati_deps = [cli_dep, boost_dep, doctest_dep, eigen_dep, fstlib_dep, librandom_dep, json_dep] +libcoati_deps = [cli_dep, boost_dep, doctest_dep, eigen_dep, fst_dep, librandom_dep, json_dep] libcoati = static_library('coati', [libcoati_sources, version_file], include_directories : inc, diff --git a/src/meson.build b/src/meson.build index a8e7335..98d283f 100644 --- a/src/meson.build +++ b/src/meson.build @@ -56,6 +56,51 @@ json_dep = dependency('json', include_type : 'system' ) +# OpenFst: an installed one when it works, else OpenFst 1.8.5 downloaded and +# built by Meson (subprojects/openfst.wrap). OpenFst installs no pkg-config +# or CMake file, so an installed library is used only if a program using +# OpenFst the way COATi does links against it. 1.8.2 and 1.8.3 do not: their +# fst/fst.h assigns a raw pointer to a std::unique_ptr, which current +# compilers reject. +openfst_check = ''' +#include + +int main() { + fst::StdVectorFst a; + const auto s = a.AddState(); + const auto t = a.AddState(); + a.SetStart(s); + a.AddArc(s, fst::StdArc(1, 1, 0.5, t)); + a.SetFinal(t, 0.0); + fst::EncodeMapper encoder(fst::kEncodeLabels); + fst::Encode(&a, &encoder); + fst::Decode(&a, encoder); + fst::StdVectorFst b; + fst::Compose(a, a, &b); + fst::StdVectorFst path; + fst::ShortestPath(b, &path); + fst::SymbolTable symbols; + symbols.AddSymbol("A"); + return fst::Verify(path) && symbols.Find("A") == 0 ? 0 : 1; +} +''' +cxx = meson.get_compiler('cpp') +openfst_opt = get_option('system_openfst') +fst_dep = dependency('', required : false) +if not openfst_opt.disabled() + fst_lib = cxx.find_library('fst', has_headers : ['fst/fstlib.h'], + required : openfst_opt) + if fst_lib.found() and cxx.links(openfst_check, dependencies : fst_lib, + name : 'installed OpenFst works with COATi') + fst_dep = fst_lib + elif openfst_opt.enabled() + error('system_openfst=enabled, but no installed OpenFst (1.8.4 or later) links a test program') + endif +endif +if not fst_dep.found() + fst_dep = subproject('openfst').get_variable('fst_dep') +endif + subdir('lib') progs=['alignpair', 'genseed', 'msa', 'version', 'sample', 'format'] diff --git a/subprojects/openfst.wrap b/subprojects/openfst.wrap new file mode 100644 index 0000000..56911f4 --- /dev/null +++ b/subprojects/openfst.wrap @@ -0,0 +1,9 @@ +[wrap-file] +directory = openfst-1.8.5 +source_url = https://www.openfst.org/twiki/pub/FST/FstDownload/openfst-1.8.5.tar.gz +source_filename = openfst-1.8.5.tar.gz +source_hash = 895f98d04e98815b6c5c6b94427d112300f2996f14687b2a2bd536d9bd0ff7ec +patch_directory = openfst + +[provide] +fst = fst_dep diff --git a/subprojects/packagefiles/openfst/meson.build b/subprojects/packagefiles/openfst/meson.build new file mode 100644 index 0000000..5c6b1d6 --- /dev/null +++ b/subprojects/packagefiles/openfst/meson.build @@ -0,0 +1,22 @@ +# OpenFst's core library, libfst, built from the release tarball +# subprojects/openfst.wrap downloads: the sources of OpenFst's own +# src/lib/Makefile.am, as a static library. +project('openfst', 'cpp', + version : '1.8.5', + license : 'Apache-2.0', + meson_version : '>=0.58.0', + default_options : ['cpp_std=c++17']) + +fst_lib = static_library('fst', + ['src/lib/compat.cc', 'src/lib/encode.cc', 'src/lib/flags.cc', + 'src/lib/fst-types.cc', 'src/lib/fst.cc', 'src/lib/mapped-file.cc', + 'src/lib/properties.cc', 'src/lib/symbol-table-ops.cc', + 'src/lib/symbol-table.cc', 'src/lib/util.cc', 'src/lib/weight.cc'], + include_directories : include_directories('src/include'), + override_options : ['warning_level=0'] +) + +fst_dep = declare_dependency( + include_directories : include_directories('src/include', is_system : true), + link_with : fst_lib +)