add get_shengmu/yunmu_string
[platform/upstream/libpinyin.git] / src / storage / ngram.cpp
1 /* 
2  *  libpinyin
3  *  Library to deal with pinyin.
4  *  
5  *  Copyright (C) 2006-2007 Peng Wu
6  *  
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  * 
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  *  GNU General Public License for more details.
16  *  
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20  */
21
22 #include <stdio.h>
23 #include <errno.h>
24 #include <glib.h>
25 #include <glib/gstdio.h>
26 #include "memory_chunk.h"
27 #include "novel_types.h"
28 #include "ngram.h"
29
30 using namespace pinyin;
31
32 struct SingleGramItem{
33     phrase_token_t m_token;
34     guint32 m_freq;
35 };
36
37 SingleGram::SingleGram(){
38     m_chunk.set_size(sizeof(guint32));
39     memset(m_chunk.begin(), 0, sizeof(guint32));
40 }
41
42 SingleGram::SingleGram(void * buffer, size_t length){
43     m_chunk.set_chunk(buffer, length, NULL);
44 }
45
46 bool SingleGram::get_total_freq(guint32 & total) const{
47     char * buf_begin = (char *)m_chunk.begin();
48     total = *((guint32 *)buf_begin);
49     return true;
50 }
51
52 bool SingleGram::set_total_freq(guint32 total){
53     char * buf_begin = (char *)m_chunk.begin();
54     *((guint32 *)buf_begin) = total;
55     return true;
56 }
57
58 guint32 SingleGram::get_length(){
59     /* get the number of items. */
60     const SingleGramItem * begin = (const SingleGramItem *)
61         ((const char *)(m_chunk.begin()) + sizeof(guint32));
62     const SingleGramItem * end = (const SingleGramItem *) m_chunk.end();
63
64     const guint32 length = end - begin;
65
66     if (0 == length) {
67         /* no items here, total freq should be zero. */
68         guint32 total_freq = 0;
69         assert(get_total_freq(total_freq));
70         assert(0 == total_freq);
71     }
72
73     return length;
74 }
75
76 guint32 SingleGram::mask_out(phrase_token_t mask, phrase_token_t value){
77     guint32 removed_items = 0;
78
79     guint32 total_freq = 0;
80     assert(get_total_freq(total_freq));
81
82     const SingleGramItem * begin = (const SingleGramItem *)
83         ((const char *)(m_chunk.begin()) + sizeof(guint32));
84     const SingleGramItem * end = (const SingleGramItem *) m_chunk.end();
85
86     for (const SingleGramItem * cur = begin; cur != end; ++cur) {
87         if ((cur->m_token & mask) != value)
88             continue;
89
90         total_freq -= cur->m_freq;
91         size_t offset = sizeof(guint32) +
92             sizeof(SingleGramItem) * (cur - begin);
93         m_chunk.remove_content(offset, sizeof(SingleGramItem));
94
95         /* update chunk end. */
96         end = (const SingleGramItem *) m_chunk.end();
97         ++removed_items;
98         --cur;
99     }
100
101     assert(set_total_freq(total_freq));
102     return removed_items;
103 }
104
105 bool SingleGram::prune(){
106     assert(false);
107 #if 0
108     SingleGramItem * begin = (SingleGramItem *)
109         ((const char *)(m_chunk.begin()) + sizeof(guint32));
110     SingleGramItem * end = (SingleGramItem *)m_chunk.end();
111     
112     size_t nitem = 0;
113     for ( SingleGramItem * cur = begin; cur != end; ++cur){
114         cur->m_freq--;
115         nitem++;
116         if ( cur->m_freq == 0 ){
117             size_t offset = sizeof(guint32) + (cur - begin)
118                 * sizeof(SingleGramItem) ;
119             m_chunk.remove_content(offset, sizeof(SingleGramItem));
120         }
121     }
122     guint32 total_freq;
123     assert(get_total_freq(total_freq));
124     assert(set_total_freq(total_freq - nitem));
125 #endif
126         return true;
127 }
128
129 static bool token_less_than(const SingleGramItem & lhs,const SingleGramItem & rhs){
130     return lhs.m_token < rhs.m_token;
131 }
132
133 bool SingleGram::retrieve_all(/* out */ BigramPhraseWithCountArray array)
134     const {
135     const SingleGramItem * begin = (const SingleGramItem *)
136         ((const char *)(m_chunk.begin()) + sizeof(guint32));
137     const SingleGramItem * end = (const SingleGramItem *) m_chunk.end();
138
139     guint32 total_freq;
140     BigramPhraseItemWithCount bigram_item_with_count;
141     assert(get_total_freq(total_freq));
142
143     for ( const SingleGramItem * cur_item = begin; cur_item != end; ++cur_item){
144         bigram_item_with_count.m_token = cur_item->m_token;
145         bigram_item_with_count.m_count = cur_item->m_freq;
146         bigram_item_with_count.m_freq = cur_item->m_freq / (gfloat)total_freq;
147         g_array_append_val(array, bigram_item_with_count);
148     }
149
150     return true;
151 }
152
153 bool SingleGram::search(/* in */ PhraseIndexRange * range,
154                         /* out */ BigramPhraseArray array) const {
155     const SingleGramItem * begin = (const SingleGramItem *)
156         ((const char *)(m_chunk.begin()) + sizeof(guint32));
157     const SingleGramItem * end = (const SingleGramItem *)m_chunk.end();
158
159     SingleGramItem compare_item;
160     compare_item.m_token = range->m_range_begin;
161     const SingleGramItem * cur_item = std_lite::lower_bound(begin, end, compare_item, token_less_than);
162
163     guint32 total_freq;
164     BigramPhraseItem bigram_item;
165     assert(get_total_freq(total_freq));
166
167     for ( ; cur_item != end; ++cur_item){
168         if ( cur_item->m_token >= range->m_range_end )
169             break;
170         bigram_item.m_token = cur_item->m_token;
171         bigram_item.m_freq = cur_item->m_freq / (gfloat)total_freq;
172         g_array_append_val(array, bigram_item);
173     }
174
175     return true;
176 }
177
178 bool SingleGram::insert_freq( /* in */ phrase_token_t token,
179                               /* in */ guint32 freq){
180     SingleGramItem * begin = (SingleGramItem *)
181         ((const char *)(m_chunk.begin()) + sizeof(guint32));
182     SingleGramItem * end = (SingleGramItem *) m_chunk.end();
183     SingleGramItem compare_item;
184     compare_item.m_token = token;
185     SingleGramItem * cur_item = std_lite::lower_bound(begin, end, compare_item, token_less_than);
186
187     SingleGramItem insert_item;
188     insert_item.m_token = token;
189     insert_item.m_freq = freq;
190     for ( ; cur_item != end; ++cur_item ){
191         if ( cur_item->m_token > token ){
192             size_t offset = sizeof(guint32) +
193                 sizeof(SingleGramItem) * (cur_item - begin);
194             m_chunk.insert_content(offset, &insert_item,
195                                    sizeof(SingleGramItem));
196             return true;
197         }
198         if ( cur_item->m_token == token ){
199             return false;
200         }
201     }
202     m_chunk.insert_content(m_chunk.size(), &insert_item,
203                            sizeof(SingleGramItem));
204     return true;
205 }
206
207 bool SingleGram::remove_freq( /* in */ phrase_token_t token,
208                               /* out */ guint32 & freq){
209     freq = 0;
210     const SingleGramItem * begin = (const SingleGramItem *)
211         ((const char *)(m_chunk.begin()) + sizeof(guint32));
212     const SingleGramItem * end = (const SingleGramItem *)m_chunk.end();
213     SingleGramItem compare_item;
214     compare_item.m_token = token;
215     const SingleGramItem * cur_item = std_lite::lower_bound(begin, end, compare_item, token_less_than);
216
217     for ( ; cur_item != end; ++cur_item ){
218         if ( cur_item->m_token > token )
219             return false;
220         if ( cur_item->m_token == token ){
221             freq = cur_item -> m_freq;
222             size_t offset = sizeof(guint32) +
223                 sizeof(SingleGramItem) * (cur_item - begin);
224             m_chunk.remove_content(offset, sizeof(SingleGramItem));
225             return true;
226         }
227     }
228     return false;
229 }
230
231 bool SingleGram::get_freq(/* in */ phrase_token_t token,
232                           /* out */ guint32 & freq) const {
233     freq = 0;
234     const SingleGramItem * begin = (const SingleGramItem *)
235         ((const char *)(m_chunk.begin()) + sizeof(guint32));
236     const SingleGramItem * end = (const SingleGramItem *)m_chunk.end();
237     SingleGramItem compare_item;
238     compare_item.m_token = token;
239     const SingleGramItem * cur_item = std_lite::lower_bound(begin, end, compare_item, token_less_than);
240     
241     for ( ; cur_item != end; ++cur_item){
242         if ( cur_item->m_token > token )
243             return false;
244         if ( cur_item->m_token == token ){
245             freq = cur_item -> m_freq;
246             return true;
247         }
248     }
249     return false;
250 }
251
252 bool SingleGram::set_freq( /* in */ phrase_token_t token,
253                            /* in */ guint32 freq){
254     SingleGramItem * begin = (SingleGramItem *)
255         ((const char *)(m_chunk.begin()) + sizeof(guint32));
256     SingleGramItem * end = (SingleGramItem *)m_chunk.end();
257     SingleGramItem compare_item;
258     compare_item.m_token = token;
259     SingleGramItem * cur_item = std_lite::lower_bound(begin, end, compare_item, token_less_than);
260     
261     for ( ;cur_item != end; ++cur_item){
262         if ( cur_item->m_token > token ){
263             return false;
264         }
265         if ( cur_item->m_token == token ){
266             cur_item -> m_freq = freq;
267             return true;
268         }
269     }
270     return false;
271 }
272
273 bool Bigram::load_db(const char * dbfile){
274     reset();
275
276     /* create in memory db. */
277     int ret = db_create(&m_db, NULL, 0);
278     assert(ret == 0);
279
280     ret = m_db->open(m_db, NULL, NULL, NULL,
281                      DB_HASH, DB_CREATE, 0600);
282     if ( ret != 0 )
283         return false;
284
285     /* load db into memory. */
286     DB * tmp_db = NULL;
287     ret = db_create(&tmp_db, NULL, 0);
288     assert(ret == 0);
289
290     ret = tmp_db->open(tmp_db, NULL, dbfile, NULL,
291                        DB_HASH, DB_RDONLY, 0600);
292     if ( ret != 0 )
293         return false;
294
295     DBC * cursorp = NULL;
296     DBT key, data;
297     /* Get a cursor */
298     tmp_db->cursor(tmp_db, NULL, &cursorp, 0);
299
300     /* Initialize our DBTs. */
301     memset(&key, 0, sizeof(DBT));
302     memset(&data, 0, sizeof(DBT));
303
304     /* Iterate over the database, retrieving each record in turn. */
305     while ((ret = cursorp->c_get(cursorp, &key, &data, DB_NEXT)) == 0) {
306         int ret = m_db->put(m_db, NULL, &key, &data, 0);
307         assert(ret == 0);
308     }
309     assert (ret == DB_NOTFOUND);
310
311     /* Cursors must be closed */
312     if ( cursorp != NULL )
313         cursorp->c_close(cursorp);
314
315     if ( tmp_db != NULL )
316         tmp_db->close(tmp_db, 0);
317
318     return true;
319 }
320
321 bool Bigram::save_db(const char * dbfile){
322     DB * tmp_db = NULL;
323
324     int ret = unlink(dbfile);
325     if ( ret != 0 && errno != ENOENT)
326         return false;
327
328     ret = db_create(&tmp_db, NULL, 0);
329     assert(ret == 0);
330
331     ret = tmp_db->open(tmp_db, NULL, dbfile, NULL,
332                        DB_HASH, DB_CREATE, 0600);
333     if ( ret != 0 )
334         return false;
335
336     DBC * cursorp = NULL;
337     DBT key, data;
338     /* Get a cursor */
339     m_db->cursor(m_db, NULL, &cursorp, 0);
340
341     /* Initialize our DBTs. */
342     memset(&key, 0, sizeof(DBT));
343     memset(&data, 0, sizeof(DBT));
344
345     /* Iterate over the database, retrieving each record in turn. */
346     while ((ret = cursorp->c_get(cursorp, &key, &data, DB_NEXT)) == 0) {
347         int ret = tmp_db->put(tmp_db, NULL, &key, &data, 0);
348         assert(ret == 0);
349     }
350     assert (ret == DB_NOTFOUND);
351
352     /* Cursors must be closed */
353     if ( cursorp != NULL )
354         cursorp->c_close(cursorp);
355
356     if ( tmp_db != NULL )
357         tmp_db->close(tmp_db, 0);
358
359     return true;
360 }
361
362 bool Bigram::attach(const char * dbfile, guint32 flags){
363     reset();
364     u_int32_t db_flags = 0;
365
366     if ( flags & ATTACH_READONLY )
367         db_flags |= DB_RDONLY;
368     if ( flags & ATTACH_READWRITE )
369         assert( !( flags & ATTACH_READONLY ) );
370     if ( flags & ATTACH_CREATE )
371         db_flags |= DB_CREATE;
372
373     if ( !dbfile )
374         return false;
375     int ret = db_create(&m_db, NULL, 0);
376     if ( ret != 0 )
377         assert(false);
378         
379     ret = m_db->open(m_db, NULL, dbfile, NULL,
380                      DB_HASH, db_flags, 0644);
381     if ( ret != 0)
382         return false;
383
384     return true;
385 }
386
387 bool Bigram::load(phrase_token_t index, SingleGram * & single_gram){
388     single_gram = NULL;
389     if ( !m_db )
390         return false;
391
392     DBT db_key;
393     memset(&db_key, 0, sizeof(DBT));
394     db_key.data = &index;
395     db_key.size = sizeof(phrase_token_t);
396
397     DBT db_data;
398     memset(&db_data, 0, sizeof(DBT));
399     int ret = m_db->get(m_db, NULL, &db_key, &db_data, 0);
400     if ( ret != 0 )
401         return false;
402
403     single_gram = new SingleGram(db_data.data, db_data.size);
404     return true;
405 }
406
407 bool Bigram::store(phrase_token_t index, SingleGram * single_gram){
408     if ( !m_db )
409         return false;
410
411     DBT db_key;
412     memset(&db_key, 0, sizeof(DBT));
413     db_key.data = &index;
414     db_key.size = sizeof(phrase_token_t);
415     DBT db_data;
416     memset(&db_data, 0, sizeof(DBT));
417     db_data.data = single_gram->m_chunk.begin();
418     db_data.size = single_gram->m_chunk.size();
419     
420     int ret = m_db->put(m_db, NULL, &db_key, &db_data, 0);
421     return ret == 0;
422 }
423
424 bool Bigram::remove(/* in */ phrase_token_t index){
425     if ( !m_db )
426         return false;
427
428     DBT db_key;
429     memset(&db_key, 0, sizeof(DBT));
430     db_key.data = &index;
431     db_key.size = sizeof(phrase_token_t);
432
433     int ret = m_db->del(m_db, NULL, &db_key, 0);
434     return 0 == ret;
435 }
436
437 bool Bigram::get_all_items(GArray * items){
438     g_array_set_size(items, 0);
439
440     if ( !m_db )
441         return false;
442
443     DBC * cursorp = NULL;
444     DBT key, data;
445     int ret;
446     /* Get a cursor */
447     m_db->cursor(m_db, NULL, &cursorp, 0); 
448
449     /* Initialize our DBTs. */
450     memset(&key, 0, sizeof(DBT));
451     memset(&data, 0, sizeof(DBT));
452         
453     /* Iterate over the database, retrieving each record in turn. */
454     while ((ret = cursorp->c_get(cursorp, &key, &data, DB_NEXT)) == 0) {
455         assert(key.size == sizeof(phrase_token_t));
456         phrase_token_t * token = (phrase_token_t *)key.data;
457         g_array_append_val(items, *token);
458     }
459
460     assert (ret == DB_NOTFOUND);
461
462     /* Cursors must be closed */
463     if (cursorp != NULL) 
464         cursorp->c_close(cursorp); 
465
466     return true;
467 }
468
469 bool Bigram::mask_out(phrase_token_t mask, phrase_token_t value){
470     GArray * items = g_array_new(FALSE, FALSE, sizeof(phrase_token_t));
471
472     if (!get_all_items(items)) {
473         g_array_free(items, TRUE);
474         return false;
475     }
476
477     for (size_t i = 0; i < items->len; ++i) {
478         phrase_token_t index = g_array_index(items, phrase_token_t, i);
479
480         if ((index & mask) == value) {
481             assert(remove(index));
482             continue;
483         }
484
485         SingleGram * gram = NULL;
486         assert(load(index, gram));
487
488         int num = gram->mask_out(mask, value);
489         if (0 == num) {
490             delete gram;
491             continue;
492         }
493
494         if (0 == gram->get_length()) {
495             assert(remove(index));
496         } else {
497             assert(store(index, gram));
498         }
499
500         delete gram;
501     }
502
503     g_array_free(items, TRUE);
504     return true;
505 }
506
507
508 namespace pinyin{
509
510 /* merge origin system info and delta user info */
511 bool merge_single_gram(SingleGram * merged, const SingleGram * system,
512                        const SingleGram * user){
513     if (NULL == system && NULL == user)
514         return false;
515
516     MemoryChunk & merged_chunk = merged->m_chunk;
517
518     if (NULL == system) {
519         merged_chunk.set_chunk(user->m_chunk.begin(),
520                                user->m_chunk.size(), NULL);
521         return true;
522     }
523
524     if (NULL == user) {
525         merged_chunk.set_chunk(system->m_chunk.begin(),
526                                system->m_chunk.size(), NULL);
527         return true;
528     }
529
530     /* clear merged. */
531     merged_chunk.set_size(sizeof(guint32));
532
533     /* merge the origin info and delta info */
534     guint32 system_total, user_total;
535     assert(system->get_total_freq(system_total));
536     assert(user->get_total_freq(user_total));
537     const guint32 merged_total = system_total + user_total;
538     merged_chunk.set_content(0, &merged_total, sizeof(guint32));
539
540     const SingleGramItem * cur_system = (const SingleGramItem *)
541         (((const char *)(system->m_chunk.begin())) + sizeof(guint32));
542     const SingleGramItem * system_end = (const SingleGramItem *)
543         system->m_chunk.end();
544
545     const SingleGramItem * cur_user = (const SingleGramItem *)
546         (((const char *)(user->m_chunk.begin())) + sizeof(guint32));
547     const SingleGramItem * user_end = (const SingleGramItem *)
548         user->m_chunk.end();
549
550     while (cur_system < system_end && cur_user < user_end) {
551
552         if (cur_system->m_token < cur_user->m_token) {
553             /* do append operation here */
554             merged_chunk.append_content(cur_system, sizeof(SingleGramItem));
555             cur_system++;
556         } else if (cur_system->m_token > cur_user->m_token) {
557             /* do append operation here */
558             merged_chunk.append_content(cur_user, sizeof(SingleGramItem));
559             cur_user++;
560         } else {
561             assert(cur_system->m_token == cur_user->m_token);
562
563             SingleGramItem merged_item;
564             merged_item.m_token = cur_system->m_token;
565             merged_item.m_freq = cur_system->m_freq + cur_user->m_freq;
566
567             merged_chunk.append_content(&merged_item, sizeof(SingleGramItem));
568             cur_system++; cur_user++;
569         }
570     }
571
572     /* add remained items. */
573     while (cur_system < system_end) {
574         merged_chunk.append_content(cur_system, sizeof(SingleGramItem));
575         cur_system++;
576     }
577
578     while (cur_user < user_end) {
579         merged_chunk.append_content(cur_user, sizeof(SingleGramItem));
580         cur_user++;
581     }
582
583     return true;
584 }
585
586 };