FST  openfst-1.8.2
OpenFst Library
partition.h
Go to the documentation of this file.
1 // Copyright 2005-2020 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the 'License');
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an 'AS IS' BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // See www.openfst.org for extensive documentation on this weighted
16 // finite-state transducer library.
17 //
18 // Functions and classes to create a partition of states.
19 
20 #ifndef FST_PARTITION_H_
21 #define FST_PARTITION_H_
22 
23 #include <algorithm>
24 #include <type_traits>
25 #include <vector>
26 
27 
28 #include <fst/queue.h>
29 
30 
31 namespace fst {
32 namespace internal {
33 
34 template <typename T>
36 
37 // Defines a partitioning of elements, used to represent equivalence classes
38 // for FST operations like minimization. T must be a signed integer type.
39 //
40 // The elements are numbered from 0 to num_elements - 1.
41 // Initialize(num_elements) sets up the class for a given number of elements.
42 // We maintain a partition of these elements into classes. The classes are also
43 // numbered from zero; you can add a class with AddClass(), or add them in bulk
44 // with AllocateClasses(num_classes). Initially the elements are not assigned
45 // to any class; you set up the initial mapping from elements to classes by
46 // calling Add(element_id, class_id). You can also move an element to a
47 // different class by calling Move(element_id, class_id).
48 //
49 // We also support a rather specialized interface that allows you to efficiently
50 // split classes in the Hopcroft minimization algorithm. This maintains a
51 // binary partition of each class. Let's call these, rather arbitrarily, the
52 // 'yes' subset and the 'no' subset of each class, and assume that by default,
53 // each element of a class is in its 'no' subset. When one calls
54 // SplitOn(element_id), element_id is moved to the 'yes' subset of its class.
55 // (If it was already in the 'yes' set, it just stays there). The aim is to
56 // enable (later) splitting the class in two in time no greater than the time
57 // already spent calling SplitOn() for that class. We keep a list of the classes
58 // which have nonempty 'yes' sets, as visited_classes_. When one calls
59 // FinalizeSplit(Queue *l), for each class in visited_classes_ whose 'yes'
60 // and 'no' sets are both nonempty, it will create a new class consisting of
61 // the smaller of the two subsets (and this class will be added to the queue),
62 // and the old class will now be the larger of the two subsets. This call also
63 // resets all the yes/no partitions so that everything is in the 'no' subsets.
64 //
65 // One cannot use the Move() function if SplitOn() has been called without
66 // a subsequent call to FinalizeSplit()
67 template <typename T>
68 class Partition {
69  static_assert(std::is_signed_v<T> && std::is_integral_v<T>,
70  "T must be a signed integer type");
71 
72  public:
73  Partition() {}
74 
75  explicit Partition(T num_elements) { Initialize(num_elements); }
76 
77  // Creates an empty partition for num_elements. This means that the elements
78  // are not assigned to a class (i.e class_index = -1); you should set up the
79  // number of classes using AllocateClasses() or AddClass(), and allocate each
80  // element to a class by calling Add(element, class_id).
81  void Initialize(size_t num_elements) {
82  elements_.resize(num_elements);
83  classes_.reserve(num_elements);
84  classes_.clear();
85  yes_counter_ = 1;
86  }
87 
88  // Adds a class; returns new number of classes.
89  T AddClass() {
90  auto num_classes = classes_.size();
91  classes_.resize(num_classes + 1);
92  return num_classes;
93  }
94 
95  // Adds 'num_classes' new (empty) classes.
96  void AllocateClasses(T num_classes) {
97  classes_.resize(classes_.size() + num_classes);
98  }
99 
100  // Adds element_id to class_id. element_id should already have been allocated
101  // by calling Initialize(num_elements)---or the constructor taking
102  // num_elements---with num_elements > element_id. element_id must not
103  // currently be a member of any class; once elements have been added to a
104  // class, use the Move() method to move them from one class to another.
105  void Add(T element_id, T class_id) {
106  auto &this_element = elements_[element_id];
107  auto &this_class = classes_[class_id];
108  ++this_class.size;
109  // Adds the element to the 'no' subset of the class.
110  auto no_head = this_class.no_head;
111  if (no_head >= 0) elements_[no_head].prev_element = element_id;
112  this_class.no_head = element_id;
113  this_element.class_id = class_id;
114  // Adds to the 'no' subset of the class.
115  this_element.yes = 0;
116  this_element.next_element = no_head;
117  this_element.prev_element = -1;
118  }
119 
120  // Moves element_id from 'no' subset of its current class to 'no' subset of
121  // class class_id. This may not work correctly if you have called SplitOn()
122  // [for any element] and haven't subsequently called FinalizeSplit().
123  void Move(T element_id, T class_id) {
124  auto elements = &(elements_[0]);
125  auto &element = elements[element_id];
126  auto &old_class = classes_[element.class_id];
127  --old_class.size;
128  // Excises the element from the 'no' list of its old class, where it is
129  // assumed to be.
130  if (element.prev_element >= 0) {
131  elements[element.prev_element].next_element = element.next_element;
132  } else {
133  old_class.no_head = element.next_element;
134  }
135  if (element.next_element >= 0) {
136  elements[element.next_element].prev_element = element.prev_element;
137  }
138  // Adds to new class.
139  Add(element_id, class_id);
140  }
141 
142  // Moves element_id to the 'yes' subset of its class if it was in the 'no'
143  // subset, and marks the class as having been visited.
144  void SplitOn(T element_id) {
145  auto elements = &(elements_[0]);
146  auto &element = elements[element_id];
147  if (element.yes == yes_counter_) {
148  return; // Already in the 'yes' set; nothing to do.
149  }
150  auto class_id = element.class_id;
151  auto &this_class = classes_[class_id];
152  // Excises the element from the 'no' list of its class.
153  if (element.prev_element >= 0) {
154  elements[element.prev_element].next_element = element.next_element;
155  } else {
156  this_class.no_head = element.next_element;
157  }
158  if (element.next_element >= 0) {
159  elements[element.next_element].prev_element = element.prev_element;
160  }
161  // Adds the element to the 'yes' list.
162  if (this_class.yes_head >= 0) {
163  elements[this_class.yes_head].prev_element = element_id;
164  } else {
165  visited_classes_.push_back(class_id);
166  }
167  element.yes = yes_counter_;
168  element.next_element = this_class.yes_head;
169  element.prev_element = -1;
170  this_class.yes_head = element_id;
171  this_class.yes_size++;
172  }
173 
174  // This should be called after one has possibly called SplitOn for one or more
175  // elements, thus moving those elements to the 'yes' subset for their class.
176  // For each class that has a nontrivial split (i.e., it's not the case that
177  // all members are in the 'yes' or 'no' subset), this function creates a new
178  // class containing the smaller of the two subsets of elements, leaving the
179  // larger group of elements in the old class. The identifier of the new class
180  // will be added to the queue provided as the pointer L. This method then
181  // moves all elements to the 'no' subset of their class.
182  template <class Queue>
183  void FinalizeSplit(Queue *queue) {
184  for (const auto &visited_class : visited_classes_) {
185  const auto new_class = SplitRefine(visited_class);
186  if (new_class != -1 && queue) queue->Enqueue(new_class);
187  }
188  visited_classes_.clear();
189  // Incrementation sets all the 'yes' members of the elements to false.
190  ++yes_counter_;
191  }
192 
193  const T ClassId(T element_id) const { return elements_[element_id].class_id; }
194 
195  const size_t ClassSize(T class_id) const { return classes_[class_id].size; }
196 
197  const T NumClasses() const { return classes_.size(); }
198 
199  private:
200  friend class PartitionIterator<T>;
201 
202  // Information about a given element.
203  struct Element {
204  T class_id; // Class ID of this element.
205  T yes; // This is to be interpreted as a bool, true if it's in the
206  // 'yes' set of this class. The interpretation as bool is
207  // (yes == yes_counter_ ? true : false).
208  T next_element; // Next element in the 'no' list or 'yes' list of this
209  // class, whichever of the two we belong to (think of
210  // this as the 'next' in a doubly-linked list, although
211  // it is an index into the elements array). Negative
212  // values corresponds to null.
213  T prev_element; // Previous element in the 'no' or 'yes' doubly linked
214  // list. Negative values corresponds to null.
215  };
216 
217  // Information about a given class.
218  struct Class {
219  Class() : size(0), yes_size(0), no_head(-1), yes_head(-1) {}
220  T size; // Total number of elements in this class ('no' plus 'yes'
221  // subsets).
222  T yes_size; // Total number of elements of 'yes' subset of this class.
223  T no_head; // Index of head element of doubly-linked list in 'no' subset.
224  // Everything is in the 'no' subset until you call SplitOn().
225  // -1 means no element.
226  T yes_head; // Index of head element of doubly-linked list in 'yes' subset.
227  // -1 means no element.
228  };
229 
230  // This method, called from FinalizeSplit(), checks whether a class has to
231  // be split (a class will be split only if its 'yes' and 'no' subsets are
232  // both nonempty, but one can assume that since this function was called, the
233  // 'yes' subset is nonempty). It splits by taking the smaller subset and
234  // making it a new class, and leaving the larger subset of elements in the
235  // 'no' subset of the old class. It returns the new class if created, or -1
236  // if none was created.
237  T SplitRefine(T class_id) {
238  auto yes_size = classes_[class_id].yes_size;
239  auto size = classes_[class_id].size;
240  auto no_size = size - yes_size;
241  if (no_size == 0) {
242  // All members are in the 'yes' subset, so we don't have to create a new
243  // class, just move them all to the 'no' subset.
244  classes_[class_id].no_head = classes_[class_id].yes_head;
245  classes_[class_id].yes_head = -1;
246  classes_[class_id].yes_size = 0;
247  return -1;
248  } else {
249  auto new_class_id = classes_.size();
250  classes_.resize(classes_.size() + 1);
251  auto &old_class = classes_[class_id];
252  auto &new_class = classes_[new_class_id];
253  // The new_class will have the values from the constructor.
254  if (no_size < yes_size) {
255  // Moves the 'no' subset to new class ('no' subset).
256  new_class.no_head = old_class.no_head;
257  new_class.size = no_size;
258  // And makes the 'yes' subset of the old class ('no' subset).
259  old_class.no_head = old_class.yes_head;
260  old_class.yes_head = -1;
261  old_class.size = yes_size;
262  old_class.yes_size = 0;
263  } else {
264  // Moves the 'yes' subset to the new class (to the 'no' subset)
265  new_class.size = yes_size;
266  new_class.no_head = old_class.yes_head;
267  // Retains only the 'no' subset in the old class.
268  old_class.size = no_size;
269  old_class.yes_size = 0;
270  old_class.yes_head = -1;
271  }
272  auto elements = &(elements_[0]);
273  // Updates the 'class_id' of all the elements we moved.
274  for (auto e = new_class.no_head; e >= 0; e = elements[e].next_element) {
275  elements[e].class_id = new_class_id;
276  }
277  return new_class_id;
278  }
279  }
280 
281  // elements_[i] contains all info about the i'th element.
282  std::vector<Element> elements_;
283  // classes_[i] contains all info about the i'th class.
284  std::vector<Class> classes_;
285  // Set of visited classes to be used in split refine.
286  std::vector<T> visited_classes_;
287  // yes_counter_ is used in interpreting the 'yes' members of class Element.
288  // If element.yes == yes_counter_, we interpret that element as being in the
289  // 'yes' subset of its class. This allows us to, in effect, set all those
290  // bools to false at a stroke by incrementing yes_counter_.
291  T yes_counter_;
292 };
293 
294 // Iterates over members of the 'no' subset of a class in a partition. (When
295 // this is used, everything is in the 'no' subset).
296 template <typename T>
297 class PartitionIterator {
298  public:
299  using Element = typename Partition<T>::Element;
300 
301  PartitionIterator(const Partition<T> &partition, T class_id)
302  : partition_(partition),
303  element_id_(partition_.classes_[class_id].no_head),
304  class_id_(class_id) {}
305 
306  bool Done() { return element_id_ < 0; }
307 
308  const T Value() { return element_id_; }
309 
310  void Next() { element_id_ = partition_.elements_[element_id_].next_element; }
311 
312  void Reset() { element_id_ = partition_.classes_[class_id_].no_head; }
313 
314  private:
315  const Partition<T> &partition_;
316  T element_id_;
317  T class_id_;
318 };
319 
320 } // namespace internal
321 } // namespace fst
322 
323 #endif // FST_PARTITION_H_
const size_t ClassSize(T class_id) const
Definition: partition.h:195
void SplitOn(T element_id)
Definition: partition.h:144
void Move(T element_id, T class_id)
Definition: partition.h:123
void AllocateClasses(T num_classes)
Definition: partition.h:96
typename Partition< T >::Element Element
Definition: partition.h:299
const T NumClasses() const
Definition: partition.h:197
void Initialize(size_t num_elements)
Definition: partition.h:81
Partition(T num_elements)
Definition: partition.h:75
const T ClassId(T element_id) const
Definition: partition.h:193
void Add(T element_id, T class_id)
Definition: partition.h:105
PartitionIterator(const Partition< T > &partition, T class_id)
Definition: partition.h:301
void FinalizeSplit(Queue *queue)
Definition: partition.h:183