/
indriRetOld.cpp
601 lines (484 loc) · 19 KB
/
indriRetOld.cpp
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#include "utils.h"
#include "indri/QueryParserFactory.hpp"
#include "indri/QueryEnvironment.hpp"
#include "indri/QueryParserFactory.hpp"
#include "indri/RawScorerNodeExtractor.hpp"
#include "indri/SnippetBuilder.hpp"
using namespace Rcpp;
using namespace std;
class Index {
public:
struct Gram {
//std::vector<std::string> terms;
std::string term;
int internal_termID;
struct hash {
int operator() ( const Gram* one ) const {
indri::utility::GenericHash<const char*> h;
int accumulator = 0;
//for( size_t i=0; i<one->terms.size(); i++ ) {
accumulator *= 7;
accumulator += h( one->term.c_str() );
//}
return accumulator;
}
};
struct weight_greater {
bool operator() ( const Gram* o, const Gram* t ) const {
return t->internal_termID > o->internal_termID;
}
};
struct string_comparator {
int operator() ( const Gram* o, const Gram* t ) const {
const Gram& one = *o;
const Gram& two = *t;
/*if( one.terms.size() != two.terms.size() ) {
if( one.terms.size() < two.terms.size() ) {
return 1;
} else {
return -1;
}
}*/
//for( size_t i=0; i<one.terms.size(); i++ ) {
const std::string& oneString = one.term;//s[i];
const std::string& twoString = two.term;//s[i];
if( oneString != twoString ) {
if( oneString < twoString )
return -1;
else
return 1;
}
//}
return 0;
}
};
};
struct Results{
map<string, int> queryStems;
map<string, int> queryStemIndex;
vector<string> queryStemOrder;
arma::mat tfMatrix;
arma::vec dfVector;
arma::vec ctfVector;
};
struct GramCounts {
Gram gram;
indri::utility::greedy_vector< std::pair< int, int > > counts;
};
typedef indri::utility::HashTable< Gram*, GramCounts*, Gram::hash, Gram::string_comparator > HGram;
private:
HGram _gramTable;
std::vector<string> terms;
indri::api::QueryEnvironment environment;
indri::api::QueryAnnotation* qa;
std::vector<lemur::api::DOCID_T> documentIDs;
std::vector<indri::api::ScoredExtentResult> results;
std::vector<double> scores;
std::vector<string> extDocIDs;
string qno;
string query;
int documentLimit;
Results resultsData;
Results resultsData_nullCopy;
public:
Index(string _indexPath, bool _server) {
try {
if (_server) environment.addServer(_indexPath);
else environment.addIndex(_indexPath);
} catch (std::exception &ex) {
forward_exception_to_r(ex);
} catch (lemur::api::Exception& e) {
::Rf_error("Unable to open index");
} catch (...) {
::Rf_error("Caught unhandled exception");
}
}
// Index Environment Functions
SEXP addIndex(string _indexPath){
try {
environment.addIndex(_indexPath);
} catch (std::exception &ex) {
forward_exception_to_r(ex);
} catch (lemur::api::Exception& e) {
::Rf_error("Unable to open index");
} catch (...) {
::Rf_error("Caught unhandled exception");
}
}
SEXP addServer(string _server){
try {
environment.addServer(_server);
} catch (std::exception &ex) {
forward_exception_to_r(ex);
} catch (lemur::api::Exception& e) {
::Rf_error("Unable to open index");
} catch (...) {
::Rf_error("Caught unhandled exception");
}
}
SEXP closeIndex() {
environment.close();
return (Rcpp::wrap(true));
}
SEXP setScoringRules(string method, string parameters){
vector<string> scoringRules;
//if(method == "tfidf" || method == "Okapi" || method == "BM25" ){
// string rule = method + "," + parameters;
//environment.setBaseline(rule);
//scoringRules.push_back("");
//environment.setScoringRules(scoringRules);
//}else{
string rule = "method:" + method + "," + parameters;
scoringRules.push_back(rule);
environment.setScoringRules(scoringRules);
//}
return R_NilValue;
}
SEXP setMemory (int memory){
return R_NilValue;
}
// Run Query Functions
SEXP getRanking(string _runid="default"){
vector<string> res_qno;
vector<string> res_q0;
vector<string> res_runid;
for(int i=0; i < documentLimit; i++){
res_qno.push_back(qno);
res_q0.push_back("Q0");
res_runid.push_back(_runid);
}
return Rcpp::DataFrame::create( Named("topic")= qno,
Named("q0")= res_q0, Named("docID")= wrap(extDocIDs),
Named("rank")= seq( 1, documentLimit ),
Named("score")= wrap(scores),
Named("runID")= res_runid);
}
SEXP runQuery(string _qno, string _query, int _documentLimit, string _runid="default"){
indri::api::QueryAnnotation* qa;
qa = environment.runAnnotatedQuery(_query, _documentLimit);
std::vector<indri::api::ScoredExtentResult> results = qa->getResults();
//_logtoposterior(results);
// Extract Documents
std::vector<lemur::api::DOCID_T> documentIDs;
std::vector<double> scores;
for (size_t i = 0; i < results.size(); i++){
documentIDs.push_back(results[i].document);
scores.push_back(results[i].score);
}
vector<string> res_qno;
vector<string> res_q0;
vector<string> res_runid;
int documentLimit = _documentLimit;
for(int i=0; i < documentLimit; i++){
res_qno.push_back(qno);
res_q0.push_back("Q0");
res_runid.push_back(_runid);
}
std::vector<string> extDocIDs = environment.documentMetadata(documentIDs, "docno");
return Rcpp::DataFrame::create( Named("topic")= _qno,
Named("q0")= res_q0, Named("docID")= wrap(extDocIDs),
Named("rank")= seq( 1, documentLimit ),
Named("score")= wrap(scores),
Named("runID")= res_runid);
}
SEXP generateResultsFromSet(string _qno, string _query, vector<string> docSet){
resultsData = resultsData_nullCopy;
documentIDs.clear();
scores.clear();
extDocIDs.clear();
terms.clear();
_gramTable.clear();
results.clear();
qno = _qno;
query = _query;
documentLimit = docSet.size();
documentIDs = environment.documentIDsFromMetadata("docno", docSet);
qa = environment.runAnnotatedQuery(query, documentIDs, documentLimit);
results = qa->getResults();
_logtoposterior(results);
// Extract Documents
for (size_t i = 0; i < results.size(); i++){
scores.push_back(results[i].score);
}
extDocIDs = environment.documentMetadata(documentIDs, "docno");
updateQueryDetails(environment, resultsData, query);
countGrams();
buildStats();
return Rcpp::wrap(true);
}
SEXP generateResults(string _qno, string _query, int _documentLimit, bool stats) {
resultsData = resultsData_nullCopy;
documentIDs.clear();
scores.clear();
extDocIDs.clear();
terms.clear();
_gramTable.clear();
results.clear();
qno = _qno;
query = _query;
documentLimit = _documentLimit;
qa = environment.runAnnotatedQuery(query, _documentLimit);
results = qa->getResults();
_logtoposterior(results);
// Extract Documents
for (size_t i = 0; i < results.size(); i++){
documentIDs.push_back(results[i].document);
scores.push_back(results[i].score);
}
extDocIDs = environment.documentMetadata(documentIDs, "docno");
if(stats){
updateQueryDetails(environment, resultsData, query);
countGrams();
buildStats();
}
return Rcpp::wrap(true);
}
// Index Statistics
SEXP getDocCount() {
long res = environment.documentCount();
return Rcpp::wrap(res);
}
SEXP getTermCount() {
long res = environment.termCount();
return Rcpp::wrap(res);
}
SEXP stemTerm(string _term) {
return Rcpp::wrap(environment.stemTerm(_term));
}
SEXP docFreq(string _term) {
long res = environment.documentCount(_term);
return Rcpp::wrap(res);
}
SEXP collFreq(string _term) {
long res = environment.termCount(_term);
return Rcpp::wrap(res);
}
// Term and Query Statistics
SEXP getQueryStats(){
vector<int> qTF;
vector<int> qIndex;
for(int i=0; i < resultsData.queryStemOrder.size(); i++ ){
string term = resultsData.queryStemOrder.at(i);
qTF.push_back(resultsData.queryStems[term]);
qIndex.push_back(resultsData.queryStemIndex[term]);
}
DataFrame d = DataFrame::create( Named("qTF")= qTF,
Named("qIndex") = qIndex);
d.attr("row.names") = resultsData.queryStemOrder;
return d;
}
SEXP getTermStats(){
vector<string> statName;
statName.push_back("DocFreq");
statName.push_back("IDF");
statName.push_back("cTF");
arma::vec idf = arma::log((environment.documentCount() + 1) /
(resultsData.dfVector + 0.5));
DataFrame d = DataFrame::create(Named("DocFreq")=resultsData.dfVector,
Named("IDF")=idf,
Named("cTF")=resultsData.ctfVector);
d.attr("row.names") = terms;
return d;
}
// Other Functions
SEXP getDocTermMatrix(string termWeighting){
Rcpp::List dimnms = Rcpp::List::create(extDocIDs, terms);
if(termWeighting == "tf"){
NumericMatrix d = Rcpp::wrap(resultsData.tfMatrix);
d.attr("dimnames") = dimnms;
return d;
}else if(termWeighting == "tf_normalized"){
arma::mat tfnorm = resultsData.tfMatrix;
arma::rowvec docLen = arma::sum(tfnorm, 0);
tfnorm.each_row() /= docLen;
NumericMatrix d = Rcpp::wrap(tfnorm);
d.attr("dimnames") = dimnms;
return d;
}else if(termWeighting == "tfidf"){
arma::mat tfidfMat = resultsData.tfMatrix;
arma::vec idf = arma::log((environment.documentCount() + 1) /
(resultsData.dfVector + 0.5));
tfidfMat.each_row() %= idf.t();
NumericMatrix d = Rcpp::wrap(tfidfMat);
d.attr("dimnames") = dimnms;
return d;
}else if(termWeighting == "idf"){
}
}
SEXP generateSnippets(bool html){
vector<string> snippetString;
vector< indri::api::ParsedDocument* > pdocuments = environment.documents(documentIDs);
indri::api::SnippetBuilder sp(html);
for( size_t row=0; row < documentIDs.size(); row++ )
snippetString.push_back(sp.build(documentIDs[row], pdocuments[row], qa));
CharacterVector c = wrap(snippetString);
c.attr("names") = extDocIDs;
return c;
}
SEXP getMetaData(string metaDataKey){
vector<string> metaDataString = environment.documentMetadata(documentIDs, metaDataKey);
CharacterVector c = wrap(metaDataString);
c.attr("names") = extDocIDs;
return c;
}
SEXP getDocumentLengths(){
vector<int> docLength;
for (size_t i = 0; i < documentIDs.size(); i++)
docLength.push_back(environment.documentLength(documentIDs[i]));
return wrap(docLength);
}
// Helper Functions
void _logtoposterior(std::vector<indri::api::ScoredExtentResult> &res){
if (res.size() == 0) return;
std::vector<indri::api::ScoredExtentResult>::iterator iter;
iter = res.begin();
double K = (*iter).score;
// first is max
double sum = 0;
for (iter = res.begin(); iter != res.end(); iter++) {
sum += (*iter).score = exp(K + (*iter).score);
}
for (iter = res.begin(); iter != res.end(); iter++) {
(*iter).score /= sum;
}
}
void updateQueryDetails(indri::api::QueryEnvironment& environment,
Results& resultData,
string query){
indri::api::QueryParserWrapper *parser = indri::api::QueryParserFactory::get(query, "indri");
indri::lang::ScoredExtentNode* rootNode = parser->query();
indri::lang::RawScorerNodeExtractor extractor;
rootNode->walk(extractor);
vector<indri::lang::RawScorerNode*>& scorerNodes = extractor.getScorerNodes();
for (int i = 0; i < scorerNodes.size(); i++){
string qterm = environment.stemTerm(scorerNodes[i]->queryText());
if(environment.stemCount(qterm) == 0)
continue;
if( resultData.queryStems.find(qterm) == resultData.queryStems.end() ){
resultData.queryStems.insert(make_pair( qterm, 1));
resultData.queryStemOrder.push_back(qterm);
}
else
resultData.queryStems[qterm] += 1;
}
}
bool isValid(const string & word){
size_t length = word.size();
const char * chArray = word.c_str();
size_t pos = 0;
while (pos < length){
if(isalnum((unsigned char)*(chArray+pos)) == 0){
return false;
}
pos ++;
}
return true;
}
void countGrams() {
std::vector<indri::api::DocumentVector*> vectors =
environment.documentVectors( documentIDs );
// for each query result
for( size_t i=0; i< results.size(); i++ ) {
// run through the text, extracting n-grams
indri::api::ScoredExtentResult& result = results[i];
indri::api::DocumentVector* v = vectors[i];
std::vector<int>& positions = v->positions();
std::vector<std::string>& stems = v->stems();
std::vector< indri::api::DocumentVector::Field >& fields = v->fields();
if (result.end == 0) result.end = positions.size();
// for each word position in the text
for( int j = result.begin; j < result.end; j++ ) {
//int maxGram = std::min( _maxGrams, result.end - j );
GramCounts* newCounts = new GramCounts;
bool containsOOV = false;
// build the gram
if( positions[ j ] == 0 || (! isValid(stems[ positions[ j ] ])) ) {
containsOOV = true;
continue;
}
newCounts->gram.term = stems[ positions[ j ] ] ;
if( containsOOV ) {
// if this contanied OOV, all larger n-grams
// starting at this point also will
delete newCounts;
break;
}
GramCounts** gramCounts = 0;
gramCounts = _gramTable.find( &newCounts->gram );
if( gramCounts == 0 ) {
_gramTable.insert( &newCounts->gram, newCounts );
gramCounts = &newCounts;
} else {
delete newCounts;
}
if( (*gramCounts)->counts.size() && (*gramCounts)->counts.back().first == i ) {
// we already have some counts going for this query result, so just add this one
(*gramCounts)->counts.back().second++;
} else {
// no counts yet in this document, so add an entry
(*gramCounts)->counts.push_back( std::make_pair( i, 1 ) );
}
}
}
for (unsigned int i = 0; i < vectors.size(); i++)
delete vectors[i];
}
void buildStats() {
HGram::iterator iter;
resultsData.tfMatrix = arma::zeros<arma::mat>(results.size(),
_gramTable.size());
// Initialize the
resultsData.dfVector.set_size(_gramTable.size());
resultsData.ctfVector.set_size(_gramTable.size());
int tmpTermID = -1;
for( iter = _gramTable.begin(); iter != _gramTable.end(); iter++ ) {
double gramCount = 0;
++tmpTermID;
Gram* gram = *iter->first;
GramCounts* gramCounts = *iter->second;
gram->internal_termID = tmpTermID;
terms.push_back(gram->term);
if( resultsData.queryStems.find(gram->term) != resultsData.queryStems.end() )
resultsData.queryStemIndex[gram->term] = tmpTermID;
resultsData.ctfVector(tmpTermID) = environment.stemCount(gram->term);
resultsData.dfVector(tmpTermID) = environment.documentStemCount(gram->term);
size_t c, r;
for( r = 0, c = 0; r < results.size() && c < gramCounts->counts.size(); r++ ) {
if( gramCounts->counts[c].first == r ) {
resultsData.tfMatrix(r, tmpTermID) = gramCounts->counts[c].second;
c++;
}
}
}
_gramTable.clear();
}
};
RCPP_MODULE(Index) {
using namespace Rcpp;
class_<Index > ("Index")
.constructor<string, bool>("Default Constructor")
// Index Environment Functions
.method("addIndex", &Index::addIndex, "Test Documentation")
.method("addServer", &Index::addServer, "Test Documentation")
.method("setScoringRules", &Index::setScoringRules, "Test Documentation")
.method("setMemory", &Index::setMemory, "Test Documentation")
.method("stemTerm", &Index::stemTerm, "Test Documentation")
// Index Statistic
.method("docFreq", &Index::docFreq, "Test Documentation")
.method("collFreq", &Index::collFreq, "Test Documentation")
.method("getTermCount", &Index::getTermCount, "Test Documentation")
.method("getDocCount", &Index::getDocCount, "Test Documentation")
// Run Query Methods
.method("generateResults", &Index::generateResults, "Test Documentation")
.method("generateResultsFromSet", &Index::generateResultsFromSet, "Test Documentation")
.method("getRanking", &Index::getRanking, "Test Documentation")
.method("runQuery", &Index::runQuery, "Test Documentation")
// Term and Query Statistics
.method("getTermStats", &Index::getTermStats, "Test Documentation")
.method("getQueryStats", &Index::getQueryStats, "Test Documentation")
// Other Features
.method("getDocTermMatrix", &Index::getDocTermMatrix, "Test Documentation")
.method("getDocumentLengths", &Index::getDocumentLengths, "Test Documentation")
.method("generateSnippets", &Index::generateSnippets, "Test Documentation")
.method("getMetaData", &Index::getMetaData, "Test Documentation");
}