tesseract  4.00.00dev
dawg.cpp
Go to the documentation of this file.
1 /* -*-C-*-
2  ********************************************************************************
3  *
4  * File: dawg.c (Formerly dawg.c)
5  * Description: Use a Directed Accyclic Word Graph
6  * Author: Mark Seaman, OCR Technology
7  * Created: Fri Oct 16 14:37:00 1987
8  * Modified: Wed Jul 24 16:59:16 1991 (Mark Seaman) marks@hpgrlt
9  * Language: C
10  * Package: N/A
11  * Status: Reusable Software Component
12  *
13  * (c) Copyright 1987, Hewlett-Packard Company.
14  ** Licensed under the Apache License, Version 2.0 (the "License");
15  ** you may not use this file except in compliance with the License.
16  ** You may obtain a copy of the License at
17  ** http://www.apache.org/licenses/LICENSE-2.0
18  ** Unless required by applicable law or agreed to in writing, software
19  ** distributed under the License is distributed on an "AS IS" BASIS,
20  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  ** See the License for the specific language governing permissions and
22  ** limitations under the License.
23  *
24  *********************************************************************************/
25 /*----------------------------------------------------------------------
26  I n c l u d e s
27 ----------------------------------------------------------------------*/
28 
29 #ifdef _MSC_VER
30 #pragma warning(disable:4244) // Conversion warnings
31 #pragma warning(disable:4800) // int/bool warnings
32 #endif
33 #include "dawg.h"
34 
35 #include "cutil.h"
36 #include "dict.h"
37 #include "emalloc.h"
38 #include "helpers.h"
39 #include "strngs.h"
40 #include "tesscallback.h"
41 #include "tprintf.h"
42 
43 /*----------------------------------------------------------------------
44  F u n c t i o n s f o r D a w g
45 ----------------------------------------------------------------------*/
46 namespace tesseract {
47 
49  bool requires_complete) const {
50  if (word.length() == 0) return !requires_complete;
51  NODE_REF node = 0;
52  int end_index = word.length() - 1;
53  for (int i = 0; i < end_index; i++) {
54  EDGE_REF edge = edge_char_of(node, word.unichar_id(i), false);
55  if (edge == NO_EDGE) {
56  return false;
57  }
58  if ((node = next_node(edge)) == 0) {
59  // This only happens if all words following this edge terminate --
60  // there are no larger words. See Trie::add_word_to_dawg()
61  return false;
62  }
63  }
64  // Now check the last character.
65  return edge_char_of(node, word.unichar_id(end_index), requires_complete) !=
66  NO_EDGE;
67 }
68 
69 bool Dawg::word_in_dawg(const WERD_CHOICE &word) const {
70  return prefix_in_dawg(word, true);
71 }
72 
74  const UNICHARSET &unicharset,
75  bool enable_wildcard) const {
76  if (filename == NULL) return 0;
77 
78  FILE *word_file;
79  char string [CHARS_PER_LINE];
80  int misses = 0;
81  UNICHAR_ID wildcard = unicharset.unichar_to_id(kWildcard);
82 
83  word_file = open_file (filename, "r");
84 
85  while (fgets (string, CHARS_PER_LINE, word_file) != NULL) {
86  chomp_string(string); // remove newline
87  WERD_CHOICE word(string, unicharset);
88  if (word.length() > 0 &&
89  !word.contains_unichar_id(INVALID_UNICHAR_ID)) {
90  if (!match_words(&word, 0, 0,
91  enable_wildcard ? wildcard : INVALID_UNICHAR_ID)) {
92  tprintf("Missing word: %s\n", string);
93  ++misses;
94  }
95  } else {
96  tprintf("Failed to create a valid word from %s\n", string);
97  }
98  }
99  fclose (word_file);
100  // Make sure the user sees this with fprintf instead of tprintf.
101  if (debug_level_) tprintf("Number of lost words=%d\n", misses);
102  return misses;
103 }
104 
105 void Dawg::iterate_words(const UNICHARSET &unicharset,
107  WERD_CHOICE word(&unicharset);
108  iterate_words_rec(word, 0, cb);
109 }
110 
112  STRING s;
113  wc->string_and_lengths(&s, NULL);
114  cb->Run(s.string());
115 }
116 
117 void Dawg::iterate_words(const UNICHARSET &unicharset,
118  TessCallback1<const char *> *cb) const {
121  WERD_CHOICE word(&unicharset);
122  iterate_words_rec(word, 0, shim);
123  delete shim;
124 }
125 
126 void Dawg::iterate_words_rec(const WERD_CHOICE &word_so_far,
127  NODE_REF to_explore,
129  NodeChildVector children;
130  this->unichar_ids_of(to_explore, &children, false);
131  for (int i = 0; i < children.size(); i++) {
132  WERD_CHOICE next_word(word_so_far);
133  next_word.append_unichar_id(children[i].unichar_id, 1, 0.0, 0.0);
134  if (this->end_of_word(children[i].edge_ref)) {
135  cb->Run(&next_word);
136  }
137  NODE_REF next = next_node(children[i].edge_ref);
138  if (next != 0) {
139  iterate_words_rec(next_word, next, cb);
140  }
141  }
142 }
143 
145  NODE_REF node, UNICHAR_ID wildcard) const {
146  EDGE_REF edge;
147  inT32 word_end;
148 
149  if (wildcard != INVALID_UNICHAR_ID && word->unichar_id(index) == wildcard) {
150  bool any_matched = false;
151  NodeChildVector vec;
152  this->unichar_ids_of(node, &vec, false);
153  for (int i = 0; i < vec.size(); ++i) {
154  word->set_unichar_id(vec[i].unichar_id, index);
155  if (match_words(word, index, node, wildcard))
156  any_matched = true;
157  }
158  word->set_unichar_id(wildcard, index);
159  return any_matched;
160  } else {
161  word_end = index == word->length() - 1;
162  edge = edge_char_of(node, word->unichar_id(index), word_end);
163  if (edge != NO_EDGE) { // normal edge in DAWG
164  node = next_node(edge);
165  if (word_end) {
166  if (debug_level_ > 1) word->print("match_words() found: ");
167  return true;
168  } else if (node != 0) {
169  return match_words(word, index+1, node, wildcard);
170  }
171  }
172  }
173  return false;
174 }
175 
176 void Dawg::init(int unicharset_size) {
177  ASSERT_HOST(unicharset_size > 0);
178  unicharset_size_ = unicharset_size;
179  // Set bit masks. We will use the value unicharset_size_ as a null char, so
180  // the actual number of unichars is unicharset_size_ + 1.
181  flag_start_bit_ = ceil(log(unicharset_size_ + 1.0) / log(2.0));
183  letter_mask_ = ~(~0ull << flag_start_bit_);
186 }
187 
188 
189 /*----------------------------------------------------------------------
190  F u n c t i o n s f o r S q u i s h e d D a w g
191 ----------------------------------------------------------------------*/
192 
193 SquishedDawg::~SquishedDawg() { delete[] edges_; }
194 
196  UNICHAR_ID unichar_id,
197  bool word_end) const {
198  EDGE_REF edge = node;
199  if (node == 0) { // binary search
200  EDGE_REF start = 0;
201  EDGE_REF end = num_forward_edges_in_node0 - 1;
202  int compare;
203  while (start <= end) {
204  edge = (start + end) >> 1; // (start + end) / 2
205  compare = given_greater_than_edge_rec(NO_EDGE, word_end,
206  unichar_id, edges_[edge]);
207  if (compare == 0) { // given == vec[k]
208  return edge;
209  } else if (compare == 1) { // given > vec[k]
210  start = edge + 1;
211  } else { // given < vec[k]
212  end = edge - 1;
213  }
214  }
215  } else { // linear search
216  if (edge != NO_EDGE && edge_occupied(edge)) {
217  do {
218  if ((unichar_id_from_edge_rec(edges_[edge]) == unichar_id) &&
219  (!word_end || end_of_word_from_edge_rec(edges_[edge])))
220  return (edge);
221  } while (!last_edge(edge++));
222  }
223  }
224  return (NO_EDGE); // not found
225 }
226 
227 inT32 SquishedDawg::num_forward_edges(NODE_REF node) const {
228  EDGE_REF edge = node;
229  inT32 num = 0;
230 
231  if (forward_edge (edge)) {
232  do {
233  num++;
234  } while (!last_edge(edge++));
235  }
236 
237  return (num);
238 }
239 
240 void SquishedDawg::print_node(NODE_REF node, int max_num_edges) const {
241  if (node == NO_EDGE) return; // nothing to print
242 
243  EDGE_REF edge = node;
244  const char *forward_string = "FORWARD";
245  const char *backward_string = " ";
246 
247  const char *last_string = "LAST";
248  const char *not_last_string = " ";
249 
250  const char *eow_string = "EOW";
251  const char *not_eow_string = " ";
252 
253  const char *direction;
254  const char *is_last;
255  const char *eow;
256 
257  UNICHAR_ID unichar_id;
258 
259  if (edge_occupied(edge)) {
260  do {
261  direction =
262  forward_edge(edge) ? forward_string : backward_string;
263  is_last = last_edge(edge) ? last_string : not_last_string;
264  eow = end_of_word(edge) ? eow_string : not_eow_string;
265 
266  unichar_id = edge_letter(edge);
267  tprintf(REFFORMAT " : next = " REFFORMAT ", unichar_id = %d, %s %s %s\n",
268  edge, next_node(edge), unichar_id,
269  direction, is_last, eow);
270 
271  if (edge - node > max_num_edges) return;
272  } while (!last_edge(edge++));
273 
274  if (edge < num_edges_ &&
275  edge_occupied(edge) && backward_edge(edge)) {
276  do {
277  direction =
278  forward_edge(edge) ? forward_string : backward_string;
279  is_last = last_edge(edge) ? last_string : not_last_string;
280  eow = end_of_word(edge) ? eow_string : not_eow_string;
281 
282  unichar_id = edge_letter(edge);
283  tprintf(REFFORMAT " : next = " REFFORMAT
284  ", unichar_id = %d, %s %s %s\n",
285  edge, next_node(edge), unichar_id,
286  direction, is_last, eow);
287 
288  if (edge - node > MAX_NODE_EDGES_DISPLAY) return;
289  } while (!last_edge(edge++));
290  }
291  }
292  else {
293  tprintf(REFFORMAT " : no edges in this node\n", node);
294  }
295  tprintf("\n");
296 }
297 
298 void SquishedDawg::print_edge(EDGE_REF edge) const {
299  if (edge == NO_EDGE) {
300  tprintf("NO_EDGE\n");
301  } else {
302  tprintf(REFFORMAT " : next = " REFFORMAT
303  ", unichar_id = '%d', %s %s %s\n", edge,
304  next_node(edge), edge_letter(edge),
305  (forward_edge(edge) ? "FORWARD" : " "),
306  (last_edge(edge) ? "LAST" : " "),
307  (end_of_word(edge) ? "EOW" : ""));
308  }
309 }
310 
311 bool SquishedDawg::read_squished_dawg(TFile *file) {
312  if (debug_level_) tprintf("Reading squished dawg\n");
313 
314  // Read the magic number and check that it matches kDawgMagicNumber, as
315  // auto-endian fixing should make sure it is always correct.
316  inT16 magic;
317  if (file->FReadEndian(&magic, sizeof(magic), 1) != 1) return false;
318  if (magic != kDawgMagicNumber) {
319  tprintf("Bad magic number on dawg: %d vs %d\n", magic, kDawgMagicNumber);
320  return false;
321  }
322 
323  inT32 unicharset_size;
324  if (file->FReadEndian(&unicharset_size, sizeof(unicharset_size), 1) != 1)
325  return false;
326  if (file->FReadEndian(&num_edges_, sizeof(num_edges_), 1) != 1) return false;
327  ASSERT_HOST(num_edges_ > 0); // DAWG should not be empty
328  Dawg::init(unicharset_size);
329 
330  edges_ = new EDGE_RECORD[num_edges_];
331  if (file->FReadEndian(&edges_[0], sizeof(edges_[0]), num_edges_) !=
332  num_edges_)
333  return false;
334  if (debug_level_ > 2) {
335  tprintf("type: %d lang: %s perm: %d unicharset_size: %d num_edges: %d\n",
336  type_, lang_.string(), perm_, unicharset_size_, num_edges_);
337  for (EDGE_REF edge = 0; edge < num_edges_; ++edge) print_edge(edge);
338  }
339  return true;
340 }
341 
342 NODE_MAP SquishedDawg::build_node_map(inT32 *num_nodes) const {
343  EDGE_REF edge;
344  NODE_MAP node_map;
345  inT32 node_counter;
346  inT32 num_edges;
347 
348  node_map = (NODE_MAP) malloc(sizeof(EDGE_REF) * num_edges_);
349 
350  for (edge = 0; edge < num_edges_; edge++) // init all slots
351  node_map [edge] = -1;
352 
353  node_counter = num_forward_edges(0);
354 
355  *num_nodes = 0;
356  for (edge = 0; edge < num_edges_; edge++) { // search all slots
357 
358  if (forward_edge(edge)) {
359  (*num_nodes)++; // count nodes links
360  node_map[edge] = (edge ? node_counter : 0);
361  num_edges = num_forward_edges(edge);
362  if (edge != 0) node_counter += num_edges;
363  edge += num_edges;
364  if (edge >= num_edges_) break;
365  if (backward_edge(edge)) while (!last_edge(edge++));
366  edge--;
367  }
368  }
369  return (node_map);
370 }
371 
373  EDGE_REF edge;
374  inT32 num_edges;
375  inT32 node_count = 0;
376  NODE_MAP node_map;
377  EDGE_REF old_index;
378  EDGE_RECORD temp_record;
379 
380  if (debug_level_) tprintf("write_squished_dawg\n");
381 
382  node_map = build_node_map(&node_count);
383 
384  // Write the magic number to help detecting a change in endianness.
385  inT16 magic = kDawgMagicNumber;
386  fwrite(&magic, sizeof(inT16), 1, file);
387  fwrite(&unicharset_size_, sizeof(inT32), 1, file);
388 
389  // Count the number of edges in this Dawg.
390  num_edges = 0;
391  for (edge=0; edge < num_edges_; edge++)
392  if (forward_edge(edge))
393  num_edges++;
394 
395  fwrite(&num_edges, sizeof(inT32), 1, file); // write edge count to file
396 
397  if (debug_level_) {
398  tprintf("%d nodes in DAWG\n", node_count);
399  tprintf("%d edges in DAWG\n", num_edges);
400  }
401 
402  for (edge = 0; edge < num_edges_; edge++) {
403  if (forward_edge(edge)) { // write forward edges
404  do {
405  old_index = next_node_from_edge_rec(edges_[edge]);
406  set_next_node(edge, node_map[old_index]);
407  temp_record = edges_[edge];
408  fwrite(&(temp_record), sizeof(EDGE_RECORD), 1, file);
409  set_next_node(edge, old_index);
410  } while (!last_edge(edge++));
411 
412  if (edge >= num_edges_) break;
413  if (backward_edge(edge)) // skip back links
414  while (!last_edge(edge++));
415 
416  edge--;
417  }
418  }
419  free(node_map);
420 }
421 
422 } // namespace tesseract
EDGE_REF * NODE_MAP
Definition: dawg.h:56
int debug_level_
Definition: dawg.h:315
virtual NODE_REF next_node(EDGE_REF edge_ref) const =0
UNICHAR_ID unichar_id(int index) const
Definition: ratngs.h:313
virtual EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id, bool word_end) const =0
Returns the edge that corresponds to the letter out of this node.
uinT64 flags_mask_
Definition: dawg.h:312
void print() const
Definition: ratngs.h:578
int32_t inT32
Definition: host.h:38
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
int UNICHAR_ID
Definition: unichar.h:33
int next_node_start_bit_
Definition: dawg.h:310
int length() const
Definition: ratngs.h:301
virtual UNICHAR_ID edge_letter(EDGE_REF edge_ref) const =0
Returns UNICHAR_ID stored in the edge indicated by the given EDGE_REF.
bool match_words(WERD_CHOICE *word, inT32 index, NODE_REF node, UNICHAR_ID wildcard) const
Definition: dawg.cpp:144
void iterate_words(const UNICHARSET &unicharset, TessCallback1< const WERD_CHOICE *> *cb) const
Definition: dawg.cpp:105
int check_for_words(const char *filename, const UNICHARSET &unicharset, bool enable_wildcard) const
Definition: dawg.cpp:73
bool end_of_word_from_edge_rec(const EDGE_RECORD &edge_rec) const
Returns true if this edge marks the end of a word.
Definition: dawg.h:225
#define tprintf(...)
Definition: tprintf.h:31
virtual void Run(A1)=0
int direction(EDGEPT *point)
Definition: vecfuncs.cpp:43
const char * string() const
Definition: strngs.cpp:198
int FReadEndian(void *buffer, int size, int count)
Definition: serialis.cpp:97
#define NUM_FLAG_BITS
Definition: dawg.h:91
void init(int unicharset_size)
Definition: dawg.cpp:176
NODE_REF next_node_from_edge_rec(const EDGE_RECORD &edge_rec) const
Returns the next node visited by following this edge.
Definition: dawg.h:212
uinT64 next_node_mask_
Definition: dawg.h:311
void append_unichar_id(UNICHAR_ID unichar_id, int blob_count, float rating, float certainty)
Definition: ratngs.cpp:446
void iterate_words_rec(const WERD_CHOICE &word_so_far, NODE_REF to_explore, TessCallback1< const WERD_CHOICE *> *cb) const
Definition: dawg.cpp:126
int size() const
Definition: genericvector.h:72
virtual void unichar_ids_of(NODE_REF node, NodeChildVector *vec, bool word_end) const =0
#define REFFORMAT
Definition: dawg.h:92
int flag_start_bit_
Definition: dawg.h:309
int16_t inT16
Definition: host.h:36
bool word_in_dawg(const WERD_CHOICE &word) const
Returns true if the given word is in the Dawg.
Definition: dawg.cpp:69
#define ASSERT_HOST(x)
Definition: errcode.h:84
void string_and_lengths(STRING *word_str, STRING *word_lengths_str) const
Definition: ratngs.cpp:427
virtual bool end_of_word(EDGE_REF edge_ref) const =0
FILE * open_file(const char *filename, const char *mode)
Definition: cutil.cpp:82
inT64 NODE_REF
Definition: dawg.h:55
EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id, bool word_end) const
Returns the edge that corresponds to the letter out of this node.
Definition: dawg.cpp:195
void chomp_string(char *str)
Definition: helpers.h:82
#define MAX_NODE_EDGES_DISPLAY
Definition: dawg.h:86
void CallWithUTF8(TessCallback1< const char *> *cb, const WERD_CHOICE *wc)
Definition: dawg.cpp:111
bool contains_unichar_id(UNICHAR_ID unichar_id) const
Definition: ratngs.cpp:304
Definition: strngs.h:45
DawgType type_
Definition: dawg.h:300
int unicharset_size_
Definition: dawg.h:308
int given_greater_than_edge_rec(NODE_REF next_node, bool word_end, UNICHAR_ID unichar_id, const EDGE_RECORD &edge_rec) const
Definition: dawg.h:250
void set_unichar_id(UNICHAR_ID unichar_id, int index)
Definition: ratngs.h:357
const char * filename
Definition: ioapi.h:38
STRING lang_
Definition: dawg.h:301
bool prefix_in_dawg(const WERD_CHOICE &prefix, bool requires_complete) const
Definition: dawg.cpp:48
static const inT16 kDawgMagicNumber
Magic number to determine endianness when reading the Dawg from file.
Definition: dawg.h:121
void write_squished_dawg(FILE *file)
Writes the squished/reduced Dawg to a file.
Definition: dawg.cpp:372
PermuterType perm_
Permuter code that should be used if the word is found in this Dawg.
Definition: dawg.h:303
uinT64 EDGE_RECORD
Definition: dawg.h:50
#define CHARS_PER_LINE
Definition: cutil.h:57
inT64 EDGE_REF
Definition: dawg.h:54
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:194
void print_node(NODE_REF node, int max_num_edges) const
Definition: dawg.cpp:240
uinT64 letter_mask_
Definition: dawg.h:313
UNICHAR_ID unichar_id_from_edge_rec(const EDGE_RECORD &edge_rec) const
Returns UNICHAR_ID recorded in this edge.
Definition: dawg.h:229