summaryrefslogtreecommitdiffstats
path: root/kbabel/kbabeldict/modules/dbsearchengine2/algorithms.cpp
blob: 466b68e5533947251ea2564e564d3862b305c53a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//
// C++ Implementation: algorithms
//
// Description: 
//
//
// Author: Andrea Rizzi <[email protected]>, (C) 2003
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "algorithms.h"
#include <tqstringlist.h>
#include <kdebug.h>

//FIXME: remove
#define i18n (const char*)

DataBaseInterface::ResultList ExactSearchAlgorithm::exec(const TQString& query )
{
    DataBaseInterface::ResultList res;
    DataBaseInterface::MainEntry e=di->get(query,0);
    
    TQStringList trs=e.second.getTranslations();
    
    for(TQStringList::iterator it=trs.begin();it!=trs.end();++it)
    {	
	
	emit newResult(QueryResult(*it,e.first.getString(),settings->scoreExact));
	
	res.push_back(QueryResult(*it));
    }
    kdDebug(0) <<"Exact algo found " << res.count() << "entries" << endl;
     return res;
}


DataBaseInterface::ResultList GenericSearchAlgorithm::exec(const TQString& query )
{
    DataBaseInterface::ResultList res;
   // ExactSearchAlgorithm exact(query,settings);
    uint countResults=0;
    for(TQValueList<AbstractSearchAlgorithm *>::iterator algoit = algoChain.begin(); algoit!=algoChain.end() && countResults < maxResults; algoit++)
	{
	connect(*algoit,TQT_SIGNAL(newResult(QueryResult)),this,TQT_SIGNAL(newResult(QueryResult)));
	kdDebug(0) << "Algo pointer" << (*algoit) << endl;
	res+=(*algoit)->exec(query);
	countResults=res.count();
	kdDebug(0) << "Count = " << countResults << endl;
	disconnect(*algoit,TQT_SIGNAL(newResult(QueryResult)),this,TQT_SIGNAL(newResult(QueryResult)));
    }
    return res;
}

void GenericSearchAlgorithm::addAlgorithm( AbstractSearchAlgorithm * algo )
{
    algoChain.append(algo);
}

DataBaseInterface::ResultList AlphaSearchAlgorithm::exec( const TQString & query )
{
    DataBaseInterface::ResultList res;
    DBItemMultiIndex::IndexList il=di->getAlpha(query);

    for(DBItemMultiIndex::IndexList::iterator it=il.begin();it!=il.end()&&!di->stopNow();++it)
    {
	DataBaseInterface::MainEntry e=di->getFromIndex(*it);
	TQStringList trs=e.second.getTranslations();
	for(TQStringList::iterator it=trs.begin();it!=trs.end() && !di->stopNow();++it)
	{
	    QueryResult r(di->format(di->simple(*it,true),query),e.first.getString(),settings->scoreAlpha);
	    emit newResult(r); 
	    res.push_back(r);
	}
    }
    kdDebug(0) <<"Alpha algo found " << res.count() << "entries" << endl;
    
    return res;
}

DataBaseInterface::ResultList SentenceArchiveSearchAlgorithm::exec( const TQString & query )
{
    DataBaseInterface::ResultList res;
    
    DataBaseInterface::MainEntry e = di->getSentence(query);
    
    TQStringList trs=e.second.getTranslations();
    
    kdDebug(0) << "Count in sentence archive " << trs.count()<< endl;
    
    for(TQStringList::iterator it=trs.begin();it!=trs.end();++it)
    {
	QueryResult r(di->format(di->simple(*it,true),query),e.first.getString(),settings->scoreSentence);
	emit newResult(r);  
	
	res.push_back(r);
    }
    kdDebug(0) <<"Sentence algo found " << res.count() << "entries" << endl;

    return res;
}

DataBaseInterface::ResultList ChunkByChunkSearchAlgorithm::exec( const TQString & query )
{
    ResultList res;
    factory->setQuery(query);
    TQPtrList<AbstractChunk> chunks=factory->chunks();
    kdDebug(0) << "Number of chunks " << chunks.count() << endl;
    chunks.setAutoDelete(true); //I should delete the chunks myself
    TQStringList querySeparators=factory->separators();

	//This prevents recursive loop.
	if (chunks.count()<=1) return res;

	TQStringList translations,tmpTranslations;

    translations.push_back("");   //FIXME this is needed to start  , but is not good
    int finalscore=0;
    int i=0;
    TQMap<TQString,bool> translationUsed;

    //Loop on all chunk
    for(AbstractChunk *it=chunks.first();it && !di->stopNow(); it=chunks.next())
    {
	kdDebug(0) << "Process next chunk" << endl;
 	int chunkscore=0;
	TQValueList<QueryResult> r=it->translations();
	 kdDebug(0) << "Number of results for this chunk " << r.count() << endl;

	if(r.count()<1) {
	    // kdDebug(0) << "Nothing found for:" << it->translations() << endl;
	    chunkscore=-10;

	}
	else
	{
	    //FIXME: check this, why 0? it is the best one?
	    chunkscore=r[0].score();
	    kdDebug(0) << "ChunkScore " << chunkscore << endl;
	    tmpTranslations.clear();


	    //Loop on results
	    translationUsed.clear();
	    for(ResultList::iterator it1=r.begin();it1!=r.end() &&!di->stopNow(); ++it1)
	    {
		TQString chunkTranslation= (*it1).result();
		if(!translationUsed.contains(chunkTranslation))
		{
		    translationUsed[chunkTranslation]=true;
		    kdDebug(0) << "a translation is: " << chunkTranslation << endl;
		    for(TQStringList::iterator it2=translations.begin();it2!=translations.end() && !di->stopNow() ; it2++)
		    {
			TQString prevTranslation=*it2;
			tmpTranslations.push_back(prevTranslation+chunkTranslation+querySeparators[i]);
			kdDebug(0) << "..appending it to " << prevTranslation << endl;
		    }
		}
	    } 
	    
	    translations=tmpTranslations; 
	
	}  
	
	//kdDebug(0) << it-> << r[0].result() << "#" << querySeparators[i] << endl;
	i++; 
	finalscore+=chunkscore;
	
	kdDebug(0) << "partial score " << finalscore;
    }
    kdDebug(0) << "this is finishd" << endl;
       if(settings->scoreChunkByChunk==0) 
	settings->scoreChunkByChunk=1;
// FIXME:fix the score system
//    finalscore/=(i*100*100/settings->scoreChunkByChunk);  //change 100 to 120(?) to lower this result (done)
    
    if (finalscore<50) return res;
    
    for(TQStringList::iterator it2=translations.begin();it2!=translations.end() && !di->stopNow() ; it2++)
    {
	TQString theTranslation=*it2;
	QueryResult qr(di->format(theTranslation,query),i18n("CHUNK BY CHUNK"),finalscore);
	qr.setRichOriginal(i18n("<h3>Chunk by chunk</h3>CHANGE THIS TEXT!!!!This translation is"
				"obtained translating the  sentences and using a"
				"fuzzy sentence translation database.<br>"
				" <b>Do not rely on it</b>. Translations may be fuzzy.<br>"));
	qr.setRichResult("<font color=#800000>"+theTranslation+"</font>") ;    
	emit newResult(qr); 
	res.push_back(qr);
    }
    
    
    return res;
    
    
}

ChunkByChunkSearchAlgorithm::ChunkByChunkSearchAlgorithm( DataBaseInterface * dbi, DBSESettings * sets ): AbstractSearchAlgorithm(dbi,sets) , factory(0) 
{
    
}


SentenceArchiveSearchAlgorithm::SentenceArchiveSearchAlgorithm( DataBaseInterface * dbi, DBSESettings * sets ): AbstractSearchAlgorithm(dbi,sets) 
{
}

FuzzyChunkSearchAlgorithm::FuzzyChunkSearchAlgorithm( DataBaseInterface * dbi, DBSESettings * sets ) : AbstractSearchAlgorithm(dbi,sets) 
{
    
}


DataBaseInterface::ResultList FuzzyChunkSearchAlgorithm::exec( const TQString & query )
{
    //FIXME: this code is shit too
    ResultList res;
    factory->setQuery(query);
    TQPtrList<AbstractChunk> querychunks = factory->chunks();
    querychunks.setAutoDelete(true);
    
    typedef TQMap<TQString,TQValueList<unsigned int> > ResultMap;
    ResultMap rmap;  //result of words index query
    unsigned int notfound=0,frequent=0,nchunks = querychunks.count();
    
    //Get index list for each word
    for(AbstractChunk *it=querychunks.first(); it &&!di->stopNow() ;  it=querychunks.next()  )
    { 
	TQValueList<uint> locations = (*it).locationReferences();
	
	if(locations.count()>0)
	{
	    rmap[(*it).chunkString()] = locations;
	    
	    if(locations.count()>1000)  //FIXME NORMALIZE THIS!!!
	    {
		frequent++;
		kdDebug(0) << "\""<<(*it).chunkString()  << "\" is frequent" <<endl;
	    }
	}
	else
	    notfound++;
	
    }
    
    
    //Now we have a map (rmap)  "word in query->list of occurency"
    
    TQValueList<unsigned int>::iterator countpos[nchunks+1];
    
    
    TQValueList<unsigned int> il;
    for(int i = 0;i<=nchunks&&!di->stopNow();i++) 
	countpos[i]=il.end();
    
    unsigned int bestcount=0;
    while(!rmap.isEmpty())
    {
	unsigned int ref,count;
	ref=(unsigned int)-1; 
	count=0;
	
	
	//This will find the min head and count how many times it occurs
	for(ResultMap::iterator it = rmap.begin();it!=rmap.end()&&!di->stopNow();++it)
	{
	    unsigned int thisref=it.data().first();
	    if(thisref<ref)
	    {
		ref=thisref;
		count=0;
	    }
	    if(thisref==ref)
	    {
		count++;
	    }
	    
	}
	
	
	for(ResultMap::iterator it = rmap.begin();it!=rmap.end()&&!di->stopNow();)
	{
	    it.data().remove(ref);
	    
	    //kdDebug(0)<< ((frequent<(nwords-notfound)) && (it.data().count()>350)) <<endl;
	    //FIXME: I think the frequent word check is not in the right place
	    if(it.data().isEmpty() || (((frequent+notfound)<nchunks) && (it.data().count()>1000)))  
		//very dirty hack...
	    {
		
		ResultMap::iterator it2=it;
		it++;
		rmap.remove(it2);
	    }
	    else it++;
	    
	}
	
	//This should be configurable or optimized:
	if(count>=(nchunks-notfound)*0.50 && count!=0)
	{
	    il.insert(countpos[count],ref);
	     for(unsigned int i = nchunks;i>=count;i--) 
		if(countpos[i]==countpos[count])		    
		    countpos[i]--;
	}
    }     
    
    //loop on number of words found
    int bestscore=0;
    
    for(unsigned int wf=nchunks;wf>0;wf-- ){
	for(TQValueList<unsigned int>::iterator it=countpos[wf];it!=countpos[wf-1] ;++it)
	{ //loop on entries with same number of word found
	    DataBaseInterface::MainEntry e;
	    e=di->getFromIndex(*it);
	      TQStringList trs=e.second.getTranslations();
	    for(TQStringList::iterator it=trs.begin();it!=trs.end()&&!di->stopNow();++it)
	    {		
		unsigned int cinr=factory->chunks(*it).count(); //chunk in result
		//compute a score, lets kbabel sort now, it should be fast...
		int score=90*wf/nchunks-(signed int)90*(((nchunks-cinr)>0)?(nchunks-cinr):(cinr-nchunks))/(nchunks*10);
		if(score>bestscore) bestscore=score;
		if(score>bestscore*0.40)
		{
		    // kdDebug(0) << "s: "<<score << "  wf: "<<wf<<"  nwords: "<<nwords<<" winr:  "<<winr
		    //    <<" 90*wf/nwords: "<<90*wf/nwords << "  -:" <<  90*(((nwords-winr)>0)?(nwords-winr):(winr-nwords))/(nwords*10)<< endl;
		    // FIXME: format better the richtext
		    TQString ori=e.first.getString();
		    TQString re=di->format(di->simple(*it,true),query);
		    QueryResult r(re,ori,score);
		    for(TQPtrListIterator<AbstractChunk> it(querychunks); it.current() && di->stopNow() ; ++it){
			ori=ori.replace(TQRegExp((*it)->chunkString(),false),"<font color=#000080><u><b>"+(*it)->chunkString()+"</b></u></font>");
		    }
		    r.setRichOriginal(ori);	
		    if(!di->stopNow())
			emit newResult(r); 
		    res.push_back(r);
		}
	    }	      
	}
    }	
    return res;
    
}

DataBaseInterface::ResultList CorrelationSearchAlgorithm::exec( const TQString & query )
{
    //FIXME, this code is shit.
    DataBaseInterface::ResultList res;
    if(di->words(query).count()>1) return res;
    TQMap<TQString,float> corRes = di->correlation(query,0,false);
    float max=0,max1=0,max2=0;
    TQString best,best1,best2;
    
    for(TQMap<TQString,float>::iterator it = corRes.begin(); it !=corRes.end(); ++it)
    {
	if(it.data()>max) 
	{
	    max2=max1;
	    best2=best1;
	    max1=max;
	    best1=best;
	    best = it.key(); 
	    max=it.data();
	    
	}	
	
	
    }
    if(!best.isEmpty()) 
    {
	double myscore=0.01*max*settings->scoreDynamic;
	QueryResult r(di->format(best,query),i18n("DYNAMIC DICT:"),myscore);
	r.setRichOriginal(i18n("<h3>Dynamic Dictionary</h3>This is a dynamic dictionary created"
			       " looking for correlation of original and translated words.<br>"
			       " <b>Do not rely on it</b>. Translations may be fuzzy.<br>"));
	r.setRichResult("<font size=+2 color=#A00000>"+di->format(best,query)+"</font>") ;    
	res.push_back(r);
	if(!di->stopNow()) 
	    emit newResult(r); 	
    }	
    if(!best1.isEmpty()) 
    {
	double myscore=0.01*max1*settings->scoreDynamic;     
	QueryResult r(di->format(best1,query),i18n("DYNAMIC DICT:"),myscore);
	r.setRichOriginal(i18n("<h3>Dynamic Dictionary</h3>This is a dynamic dictionary created"
			       " looking for correlation of original and translated words.<br>"
			       " <b>Do not rely on it</b>. Translations may be fuzzy.<br>"));
	r.setRichResult("<font size=+2 color=#800000>"+di->format(best1,query)+"</font>") ;    
	res.push_back(r);
	if(!di->stopNow()) 
	    emit newResult(r); 	
    }	
    
    kdDebug(0) << "Correlation algorithm found" << res.count() << "results";
    return res;
    
}

GenericSearchAlgorithm::GenericSearchAlgorithm( DataBaseInterface * dbi, DBSESettings * sets ): AbstractSearchAlgorithm(dbi,sets) 
{
    maxResults = 5; //FIXME use as default somthing from DBSESettings
}

SingleWordSearchAlgorithm::SingleWordSearchAlgorithm( DataBaseInterface * dbi, DBSESettings * sets ) : GenericSearchAlgorithm(dbi,sets),
    exact(dbi,sets), alpha(dbi,sets), sentence(dbi,sets), corr(dbi,sets), chunk(dbi,sets),casefactory(dbi)
    {
    addAlgorithm(&exact);
    addAlgorithm(&alpha);
    addAlgorithm(&sentence);
	chunk.setChunkFactory(&casefactory);
	addAlgorithm(&chunk);
	addAlgorithm(&corr);
}

DataBaseInterface::ResultList SingleWordSearchAlgorithm::exec( const TQString & query )
{
    if(di->words(query).count()>1)
	return ResultList();
    return GenericSearchAlgorithm::exec(query);
}


//#include "algorithms.moc"