-
Notifications
You must be signed in to change notification settings - Fork 4
/
SDDB.cpp
1653 lines (1415 loc) · 54.1 KB
/
SDDB.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014 Cyrus Shaoul and Geoff Hollis
This file is part of HiDEx.
HiDEx is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
HiDEx is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with HiDEx in the COPYING.txt file.
If not, see <http://www.gnu.org/licenses/>.
*/
//_LARGE_FILES is required for using large files on AIX.... Ha!
#define _LARGE_FILES
#ifdef _OPENMP
/* using conditional compilation to let sequential compilers ignore the omp.h header*/
#include <omp.h>
#endif
#include <algorithm>
#include <map>
#include <cassert>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
#include <list>
#include <set>
#include <sstream>
#include <vector>
#include <algorithm>
#include <utility>
#include <stdlib.h>
#include <fenv.h>
#include <time.h>
#include "SDDB.h"
#include "MatrixUtils.h"
#include "utilities.h"
#include "Exception.h"
#include "sys/stat.h"
using namespace std;
// ****************************************************************************
// destructor: Remove accessor
SDDB::~SDDB()
{
if(_accessor != NULL)
{
_accessor->close();
delete _accessor;
}
}
SDDB::SDDB(const string dbname, const string dbpath) {
_dbname = dbname;
_dbpath = dbpath;
_accessor = NULL;
}
// constructor: open a database to use for update or printsds
void SDDB::load(const string eod, const size_t maxMemory) {
_eod = eod;
string dbBase = _dbpath + _dbname + DBINFO_TAG;
int numVectors;
int vectorLen;
int windowLenBehind;
int windowLenAhead;
long corpussize;
readMetaData(dbBase, numVectors, vectorLen, windowLenBehind, windowLenAhead, corpussize);
cerr << "Current Corpus Size = " << corpussize << " words."<< endl;
_corpussize = corpussize;
cerr << "Checking for DB......"<< endl;
if (!dbReady(_dbname,_dbpath)) {
ostringstream buffer;
buffer << "An intact database was not found for " << _dbname << ". Cannot continue without database. Exiting." ;
throw Exception(buffer.str());
}
string accname;
// sprintf(accname, "%s/%s%s", accname, _dbname, ACCESSOR_TAG);
accname = _dbpath + _dbname + DBDIR_TAG + "/" + _dbname + ACCESSOR_TAG;
_accessor = new SDDBAccessor(accname.c_str(), numVectors, vectorLen,
windowLenBehind, windowLenAhead);
_realAhead = windowLenAhead;
_realBehind = windowLenBehind;
ostringstream dictname;
dictname << _dbpath << _dbname << DICT_TAG;
cerr << "Lexicon to be used = " << dictname.str() << endl;
build_dict_and_freqs(_dict, dictname.str(), _frequency);
build_idMap(_dict, _idMap);
if (_useVariance) {
ostringstream vardictname;
vardictname << _dbpath << _dbname << VAR_TAG;
cerr << "Variance Data to be used = " << vardictname.str() << endl;
build_variance(vardictname.str(), _variance);
}
_numwords = _dict.size();
cerr << "Number of words in Dictionary = " << _numwords << endl;
_wordNum = 0;
_currStep = 0;
_stepsize = numVectors;
}
// called when creating a brand new database
void SDDB::initialize (const string& dictfile, const int windowLenBehind, const int windowLenAhead, const string& eod) {
ofstream out;
_eod = eod;
_corpussize = 0;
string dbBase = _dbpath + _dbname + DBINFO_TAG;
string dictname = _dbpath + dictfile;
if (dbExists(dbBase)) {
ostringstream buffer;
buffer << "A database called " << _dbname << " cannot be initializeed. A file called : "<< dbBase <<" alread exists. Please remove the old data before creating a new database. Exiting." ;
throw Exception(buffer.str());
}
build_starting_dict(_dict, dictname, _frequency, _normCase);
size_t entries = _dict.size();
cerr << "Built a lexicon with " << entries << " words\n";
ostringstream accname;
accname << _dbpath << _dbname << DBDIR_TAG;
makeDir(accname.str());
ostringstream LexiconFileName;
LexiconFileName << _dbpath << _dbname << DICT_TAG;
write_dict_and_freqs(_dict, LexiconFileName.str() , _frequency);
if (_useVariance) {
ostringstream vardictname;
vardictname << _dbpath << _dbname << VAR_TAG;
build_starting_variance(_dict, vardictname.str());
}
_wordNum = 0;
int numVectors = entries;
int vectorLen = entries;
long corpussize = _corpussize;
writeMetaData(dbBase, numVectors, vectorLen, windowLenBehind, windowLenAhead, corpussize);
_currStep = 0;
_stepsize = numVectors;
_accessor = 0;
}
void SDDB::GetDocuments(istream &in, const int number, vector<string> &documents) {
string word;
ostringstream buffer;
documents.reserve(number);
for (int i = 0; i < number; i++) {
in >> word;
while ((word != _eod) && (in.good())) {
buffer << word << " ";
in >> word;
}
documents.push_back(buffer.str());
// cout << buffer.str() << endl << ":::::::::"<< endl;
buffer.str("");
}
}
// Reads in a new document from the corpus file. Returns false if document is too small.
bool SDDB::ConvertADocument(istream& in, vector<int>& wordsInDocument, const size_t behind,
const size_t ahead, const int testmode, string lang)
{
vector<int> processedwords;
vector<string> compoundword;
string word;
Numpair ids;
// clear last document
wordsInDocument.clear();
// add empty window to begining of words in document
for (size_t i = 0; i < (behind+1); i++ ) {
wordsInDocument.push_back(NO_WORD);
}
// take a word out of the document
in >> word;
while ((word != _eod) && (in.good())) {
// Clean up the word, including splitting possessives.
ids = CleanWord(word,_dict,_normCase,_englishContractions, lang);
if (ids.first) {
wordsInDocument.push_back(ids.first);
if (ids.second) {
wordsInDocument.push_back(ids.second);
}
} else {
// cerr << word << ";" << _dict[word]<< " ";
wordsInDocument.push_back(UNRECOGNIZED_WORD);
}
_wordNum++;
in >> word;
}
// add empty window to end of words in document
for (size_t i = 0; i < (ahead+2); i++ ) {
wordsInDocument.push_back(END_OF_DOCUMENT);
}
// cerr << " reached the end of document...It had " << wordsInDocument.size()<< " words.\n";
// for debugging
// for (vector<int>::iterator i = wordsInDocument.begin(); i != wordsInDocument.end(); ++i ) {
// cerr << *(i) << " ";
// }
size_t minwords;
if (testmode)
minwords = 4;
else
minwords = MIN_WORDS_PER_DOC;
if (wordsInDocument.size() > minwords)
{
// cerr << "Doc of " << wordsInDocument.size() << " words." << endl;
return true;
}
else
return false;
}
// tests a document to see if it is empty
bool SDDB::windowIsNotEmpty(vector<int>& window, size_t behind) {
if (window.at(behind) == END_OF_DOCUMENT)
return false;
else
return true;
}
// make the window when there is no window
void SDDB::makeWindow(vector<int>& window, vector<int>& wordsInDocument) {
// size_t i;
// cerr << "Words in Window = " << wordsInDocument.size() << endl;
assert(window.size() < wordsInDocument.size());
for (vector<int>::iterator i = window.begin(); i != window.end(); ++i) {
*(i)=wordsInDocument[0];
//pop element off front of vector
wordsInDocument.erase(wordsInDocument.begin(), wordsInDocument.begin()+1);
}
//for debugging
// for (vector<int>::iterator i = window.begin(); i != window.end(); ++i) {
// cerr << *(i) << " ";
// }
// cerr << endl;
}
// slide the window over one word.
void SDDB::slideWindow(vector<int>& window, vector<int>& wordsInDocument) {
//remove first element from beginning of window
window.erase(window.begin(), window.begin()+1);
//add new element to end of window.
window.push_back(wordsInDocument[0]);
//remove first element from Words in Document
wordsInDocument.erase(wordsInDocument.begin(), wordsInDocument.begin()+1);
//for debugging
// for (vector<int>::iterator i = window.begin(); i != window.end(); ++i) {
// cerr << *(i) << " ";
// }
// cerr << endl;
}
// Adds Cooccurences to raw cooccrence database
void SDDB::addCooccurrences(vector<int>& window, size_t target) {
if(window[target] != UNRECOGNIZED_WORD) {
// exclude words that are not in current step.
if ((window[target] >= _currStep) && (window[target] < (_currStep + _stepsize - 1))) {
for(size_t i = 0; (i < window.size()) && (window[i] != END_OF_DOCUMENT); i++){
// we still haven't moved far enough into the
// file to have a behind window
if(window[i] == NO_WORD)
continue;
// if we're at a word we don't recognize, skip it
else {
if(window[i] == UNRECOGNIZED_WORD)
continue;
// we're at the current word ... up its frequency and skip it
else {
if (i == target){
// cerr << "Freq for " << _idMap[window[i]] << " increased by 1" << endl;
_frequency[window[i]]++;
}
// otherwise let's update the co-occurance database
else {
// cerr << "adding data for word " << window[target] << " with " << window[i] << endl;
_accessor->add(window[target], window[i], i-target, 1);
}
}
}
}
}
}
}
void SDDB::update(istream& in, const int testmode) {
size_t ahead = _accessor->myWindowLenAhead();
size_t behind = _accessor->myWindowLenBehind();
size_t coOccurSpan = (ahead + behind + 1); // +1 for current word
vector<int> window(coOccurSpan,-6);
vector<int> wordsInDocument;
size_t documentCount = 0;
size_t badDocumentCount = 0;
bool validDocument;
vector<string> documents;
int x = 0;
_possessive = "'S";
size_t loopCount = 0;
string lang = getLang();
cerr << "Processing data between words " << _currStep << " and " << _currStep + _stepsize - 1 << endl;
_corpussize = 0;
while(in.good()) {
loopCount++;
documents.clear();
// Progress Meter
if(((x+1) % 1000) == 0) {
cerr << "Documents processed: " << FormatWithCommas(documentCount) << " _ Total Word Count: " << FormatWithCommas(_corpussize) << " _ Time: " << timestamp() << "\r" ;
cerr.flush();
}
validDocument = ConvertADocument(in, wordsInDocument, behind, ahead, testmode, lang);
if (validDocument) {
documentCount++;
makeWindow(window, wordsInDocument);
while (windowIsNotEmpty(window, behind)) {
slideWindow(window, wordsInDocument);
//#pragma omp critical
addCooccurrences(window, behind);
_corpussize++;
}
} else {
badDocumentCount++;
}
// increment progress meter
x++;
}
// cerr << endl << " Finished Processing Doc number: " << x << endl;
cerr << "\nFinished this processing step.\n " ;
//for debugging.. show Matrix
//for (size_t i = 0; i < _dict.size(); i++) {
// cerr << "Word number " << i << ":" << _idMap[i] << " \n";
// _accessor->show(i);
// }
}
Matrix<int> *SDDB::getMatrix(const char *word,
const int windowLenBehind,
const int windowLenAhead)
{
int num;
if( _dict.find(word) != _dict.end()){
num = _dict[word];
return _accessor->getMatrix(num, windowLenBehind, windowLenAhead);
}
else
return NULL;
}
int SDDB::rows() { return _accessor->myNumVectors(); }
int SDDB::columns() { return _accessor->myVectorLen(); }
int SDDB::windowLenBehind() { return _accessor->myWindowLenBehind(); }
int SDDB::windowLenAhead() { return _accessor->myWindowLenAhead(); }
void SDDB::flushDB() {
assert(_accessor);
_accessor->flush();
_wordNum = 0;
}
//called as the close the db and save state to disk
void SDDB::close() {
ostringstream dictname;
dictname << _dbpath << _dbname << DICT_TAG;
cerr << "Writing out current lexicon and frequencies." << endl;
write_dict_and_freqs(_dict, dictname.str(), _frequency);
if (_useVariance) {
// Calculate the vector variance for all words.
cerr << "Calculating Variances." << endl;
#pragma omp parallel for
for (size_t i = 0; i < _numwords ; i++) {
Matrix<int> *M = _accessor->getMatrix(i,_realBehind,_realAhead);
_variance[i] = computeVariance(M,_realBehind,_realAhead,_numwords);
// cerr << "Variance for " << i << " was " << _variance[i] << endl;
}
ostringstream vardictname;
vardictname << _dbpath << _dbname << VAR_TAG;
write_vars(_dict, vardictname.str(), _variance);
}
int numVectors = _accessor->myNumVectors();
int vectorLen = _accessor->myVectorLen();
int windowLenBehind = _accessor->myWindowLenBehind();
int windowLenAhead = _accessor->myWindowLenAhead();
long corpussize = _corpussize;
string dbBase = _dbpath + _dbname + DBINFO_TAG;;
cerr << "Writing out meta-data." << endl;
writeMetaData(dbBase, numVectors, vectorLen, windowLenBehind, windowLenAhead, corpussize);
_accessor->close();
delete _accessor;
_accessor = NULL;
}
bool SDDB::stepUp() {
_currStep += _stepsize;
if(_currStep >= rows())
return false;
return true;
}
void SDDB::setCurrentStep(int step) {
_currStep = step;
}
void SDDB::setOptions(Settings settings) {
_stepsize = settings.stepsize;
_normCase = settings.normCase;;
_englishContractions = settings.englishContractions;
_useVariance = settings.useVariance;;
_thresholdPercentile = settings.thresholdPercentile;
}
pair<string,string> SDDB::createDirectories (const string outputpath, const bool wordsout) {
// creates Directories needed for output of results.
string currenttime;
currenttime = timestamp();
string outputdir;
outputdir = outputpath + "output." + currenttime;
int resultcode = 0;
resultcode = makeDir(outputdir);
// Code added to prevent time-based file name collision problems
// This can happen when multiple HiDEx processes begin in the same working
// directory at the same time!
if (resultcode < 0) {
wait((rand()%10)+20);
currenttime = timestamp();
outputdir = outputpath + "output." + currenttime;
resultcode = makeDir(outputdir);
if (resultcode < 0) {
ostringstream buffer;
buffer << "Could not create directory: " << outputdir << " ...Exiting.";
throw Exception(buffer.str());
}
}
string subdir = outputdir + "/wordneighborhoods";
if (wordsout) {
// Subdirectory for word neighborhoods
resultcode = makeDir(subdir);
if (resultcode < 0) {
ostringstream buffer;
buffer << "Could not create directory: " << subdir << " ...Exiting.";
throw Exception(buffer.str());
}
}
pair<string,string> outputloc;
outputloc.first = outputdir;
outputloc.second = subdir;
return outputloc;
}
void SDDB::printPairs(istream &in,
const int context_size, int weightingScheme,
const int windowLenBehind, const int windowLenAhead,
const int separate,
const string outputpath,
const string metric,
const string normalization,
const int saveGCM
)
{
size_t pairs_to_print = 0;
// size_t num_dimensions = 0;
int behind = min(windowLenBehind, _realBehind);
int ahead = min(windowLenAhead, _realAhead);
int windowLen = behind + ahead;
// get all words from lexicon, put them in array of strings.
idMap words;
words = _idMap;
// create the directories
pair<string,string> outputloc = createDirectories(outputpath,0);
// collect all of the word pairs we'll be printing distances for
cerr << "Time is: " << timestamp() << endl;
cerr << "Reading in word pairs of interest" << endl;
// Load word pairs
vector<pairdata> results;
LoadPairs(in, results,_normCase);
cerr << "Loaded " << results.size() << " word pairs." << endl;
vector<pairdata> finalresults;
// Find words that are not in our lexicon from the word pairs list.
vector<pairdata>::iterator results_iter;
for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
string key1 = (*results_iter).word1;
string key2 = (*results_iter).word2;
if ( _dict.find(key1) == _dict.end() ) {
cerr << "Skipping Words " << key1 << " & " << key2 << ". Word " << key1 << " does not exist in our dictionary." << endl;
} else {
if ( _dict.find(key2) == _dict.end()) {
cerr << "Skipping Words " << key1 << " & " << key2 << ". Word " << key2 << " does not exist in our dictionary." << endl;
} else {
if ((_frequency[_dict[key1]] > 0) && (_frequency[_dict[key2]] > 0)) {
pairs_to_print++;
finalresults.push_back(*results_iter);
}
else {
cerr << "Skipping Words " << key1 << " & " << key2 <<". A Word did not appear in the corpus." << endl;
}
}
}
}
results = finalresults;
cerr << pairs_to_print << " target word pairs found" << endl;
vector<Float*> vectors(_numwords);
if (GCMexists(_dbname)) {
LoadMatrix(vectors);
} else {
//create weighting scheme
vector<int> weightScheme = createWeightScheme(windowLen, behind, weightingScheme);
//create context vector
vector<int> context = GenerateContext(context_size, separate);
//Aggregate Vectors
AggregateVectors(vectors, separate, context, behind, ahead, weightScheme, normalization);
if (saveGCM) {
SaveMatrix(vectors);
}
}
//start calculating distances
//Do in parallel!!!
int id;
size_t count = 0;
size_t numresults = results.size();
#pragma omp parallel firstprivate(count) shared(results) private(id)
{
#pragma omp for
for (size_t i=0; i < numresults; i++) {
// for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
string word1 = results[i].word1;
string word2 = results[i].word2;
int id1 = _dict[word1];
int id2 = _dict[word2];
if ((vectors[id1] == NULL) || (vectors[id2] == NULL)) {
cerr << "Tried to print SDs for, " << word1 << " and " << word2 << ", but we did not have a vector for one of them!" << endl << flush;
continue;
}
count++;
// show progress
if(((count) % 10000) == 0) {
id = omp_get_thread_num();
cerr <<" Processing pair number " << count << " for thread #" << id <<endl << flush;
}
// get inter-word distance
results[i].distance = CalcSimilarity(vectors, id1, id2, metric);
}
}
string currenttime;
wait((rand()%10)+5);
currenttime = timestamp();
string filename = outputloc.first + "/" + "pair.dists." + currenttime + ".txt";
ofstream dists;
dists.open(filename.c_str());
if(!dists.good()) {
ostringstream buffer;
buffer << "Could not create output file: " << filename << " ...Exiting.";
throw Exception(buffer.str());
}
dists << "WORD1\tWORD2\tSIMILARITY" << endl;
for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
string word1 = (*results_iter).word1;
string word2 = (*results_iter).word2;
Float distance = (*results_iter).distance;
dists << word1 << "\t" << word2 << "\t" << distance << endl;
}
dists.close();
// Open global output file.
filename = outputloc.first + "/global.txt";
ofstream global;
global.open(filename.c_str());
if(!global.good()) {
ostringstream buffer;
buffer << "Could not create output file " << filename <<" Exiting.";
throw Exception(buffer.str());
}
global << outputloc.first << "\t" << context_size << "\t" << weightingScheme << "\t" << windowLenBehind << "\t" << windowLenAhead << "\t";
global << separate << "\t" << endl;
global.close();
cerr << "Done writing results.\nBeginning to delete matrix from memory." << endl;
for(size_t i = 0; i < _numwords; i++)
if(vectors[i] != NULL)
delete [] vectors[i];
cerr << "Success. Finished processing pairs at " << timestamp() << endl;
return;
}
int SDDB::printSDs(istream &in,
const int context_size,
int weightingScheme,
const string metric, const string normalization,
const int windowLenBehind, const int windowLenAhead,
const size_t neighbourhood_size, const int usezscore,
// const int useldrt,
const int separate,
const double percenttosample, const int wordlistsize,
const string outputpath,
const int saveGCM,
const string configdata
)
{
int words_to_print = 0;
int behind = min(windowLenBehind, _realBehind);
int ahead = min(windowLenAhead, _realAhead);
int windowLen = behind+ahead;
Float threshold = 0.0;
Float average = 0.0;
Float stddev = 0.0;
// corpus size per million
Float PerMillionDivisor = static_cast<Float>(_corpussize)/1000000.0;
// get all words from lexicon, put them in array of strings.
idMap words;
words = _idMap;
// create the directories
pair<string,string> outputloc = createDirectories(outputpath,1);
cerr << "Time is: " << timestamp() << endl;
cerr << "Reading in words of interest" << endl;
// collect all of the words we'll be printing distances for
vector<resultdata> results;
//load words
LoadWords(in, wordlistsize, results , _normCase);
cerr << "Loaded " << results.size() << " words." << endl;
vector<resultdata> finalresults;
//Dictionary *words_of_interest = dictNew(50000);
Dictionary words_of_interest;
// Find words that are not in our lexicon from word list.
vector<resultdata>::iterator results_iter;
for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
string key = (*results_iter).word;
if ( _dict.find(key) != _dict.end()) {
if (_frequency[_dict[key]] > 0) {
words_to_print++;
// cerr << key << " " << id << endl;
words_of_interest[key] = _dict[key];
finalresults.push_back(*results_iter);
}
else {
cerr << "Skipping Word, " << key << ". Word did not appear in corpus." << endl;
}
}
else {
cerr << "Skipping Word, " << key << ". Word does not exist in our dictionary." << endl;
}
}
results = finalresults;
cerr << words_to_print << " target words found" << endl;
// Storage structure for GCM.
vector<Float*> vectors(_numwords);
// Look for pre-calculated GCM, and if it exists, load it.
if (GCMexists(_dbname)) {
LoadMatrix(vectors);
} else {
// If there is no pre-calculated GCM, begin creating one.
vector<int> weightScheme = createWeightScheme(windowLen, behind, weightingScheme);
if (weightScheme[0] == 0) {
return -1;
}
// Create context vector
vector<int> context = GenerateContext(context_size, separate);
// Aggregate all the raw vectors in the database, and create a GCM.
AggregateVectors(vectors, separate, context, behind, ahead, weightScheme, normalization);
// If the user desires, save the CGM for later re-use.
if (saveGCM) {
SaveMatrix(vectors);
}
}
//debugging....
// for (int x = 0; x < _numwords; x++)
// for (int y = 0; y < num_dimensions; y++)
// if (vectors[x][y] != 0.0) {
// cerr << "At: " << x << " " << y << " value: " << vectors[x][y] << endl;
// }
if (usezscore) {
cerr << "Generating random distances. Time is: " << timestamp() << endl;
threshold = GenerateStandardDev(percenttosample,vectors,average,stddev,metric);
cerr << "Got similarity threshold for neighbors, it is: " << threshold << " . Time is: " << timestamp() << endl;
}
else {
threshold = 0.0;
}
// ****************************************
// START CALCULATING VECTOR SIMILARITIES.
// ****************************************
// Calculate the similarity of each vector
// with all other vectors and print out the results
// Generate our list of words we want similarities
string filename;
// Open parameter output file.
filename = outputloc.first + "/parameters.txt";
ofstream parms;
parms.open(filename.c_str());
if(!parms.good()) {
ostringstream buffer;
buffer << "Could not create output file." << filename << " Exiting.";
throw Exception(buffer.str());
}
parms << configdata << endl;
parms << "Threshold: " << threshold << endl;
parms.close();
// Open arc output file.
filename = outputloc.first + "/ans.txt";
ofstream ans;
ans.open(filename.c_str());
if(!ans.good()) {
ostringstream buffer;
buffer << "Could not create output file." << filename << " Exiting.";
throw Exception(buffer.str());
}
ans << "WORD\tOFREQ\tANS\tNCount\tInverseNCount" << endl;
// set precision
ans.precision(15);
// Open global output file.
filename = outputloc.first + "/global.txt";
ofstream global;
global.open(filename.c_str());
if(!global.good()) {
ostringstream buffer;
buffer << "Could not create output file " << filename <<" Exiting.";
throw Exception(buffer.str());
}
// Loops through the list of words to have SDs calculated.
// size_t counter = 1;
cerr << "Completed Processing these words: ";
// Output loop
for (Dictionary::iterator i = words_of_interest.begin(); i != words_of_interest.end(); i++) {
string word = i->first;
size_t id = static_cast<size_t>(i->second);
NeighborsVector neighbours;
if(vectors[id] == NULL) {
cerr << endl << "Tried to print SDs for, " << word
<< ", but we did not have a vector for it!" << endl;
continue;
}
// Main distance calculation loop.
int limit = static_cast<int>(_numwords);
#pragma omp parallel for
for (int j = 0; j < limit; j++) {
// don't get the distance from ourself
if(id == static_cast<size_t>(j))
continue;
// don't get the distance from words with no vectors
if(vectors[j] == NULL)
continue;
// get distance
Float dist = CalcSimilarity(vectors, id, j, metric);
// atomic operation when writing.
#pragma omp critical
neighbours.push_back(NeighborhoodEntry(dist,j));
}
sort(neighbours.begin(), neighbours.end(), RevSort());
// remove all neighbors we don't need (gt than MAXNEIGHBOURS)
if (neighbours.size() > MAXNEIGHBOURS) {
size_t extras = neighbours.size() - MAXNEIGHBOURS;
for (size_t m = 0; m < extras; m++) {
neighbours.pop_back();
}
}
// print out our neighbours.
filename = outputloc.second + "/" + word + ".nbr.txt" ;
ofstream nbrs;
nbrs.open(filename.c_str());
nbrs.precision(10);
Float neighbourhood_distance = 0;
Float neighbourhood_frequency = 0;
Float freqpermillion = 0;
// Float word_magnitude = 0;
int clustercount = neighbourhood_size;
Float ANS = 0;
if (!usezscore) {
nbrs << "WORD\tNEIGHBOR\tOFREQ\tSIMILARITY" << endl;
// Get standard neighborhood
for(size_t j = 0; j < neighbourhood_size; j++) {
if(neighbours[j].second != -1) {
neighbourhood_distance += neighbours[j].first;
freqpermillion = static_cast<Float>(_frequency[neighbours[j].second]) / PerMillionDivisor;
nbrs << word << "\t"
<< words[neighbours[j].second] << "\t"
<< freqpermillion << "\t"
<< neighbours[j].first << endl;
}
}
}
else {
// get z-cluster neighborhood
nbrs << "WORD\tNEIGHBOR\tOFREQ\tSIMILARITY" << endl;
clustercount = 0;
for (size_t j=0; j < MAXNEIGHBOURS; j++) {
if(neighbours[j].second != -1) {
if (neighbours[j].first >= threshold) {
clustercount += 1;
neighbourhood_distance += neighbours[j].first;
freqpermillion = static_cast<Float>(_frequency[neighbours[j].second]) / PerMillionDivisor;
neighbourhood_frequency += freqpermillion;
nbrs << word << "\t"
<< words[neighbours[j].second] << "\t"
<< freqpermillion << "\t"
<< neighbours[j].first << endl;
}
else {
break;
}
}
}
}
// Calculate ANS
if (clustercount == 0) {
ANS = neighbours[0].first;
// Get ANS Zscore
// ANS = (ANS - average)/stddev;
}
else {
if (!usezscore) {
ANS = ( neighbourhood_distance / static_cast<Float>(neighbourhood_size) ) ;
} else {
ANS = ( neighbourhood_distance / static_cast<Float>(clustercount) ) ;
}
}
nbrs.close();
// print log entry
Float inverseclustercount = 1.0 / (1.0 + static_cast<Float>(clustercount));
//#pragma omp critical
ans << word << "\t" << (static_cast<Float>(_frequency[id]) / PerMillionDivisor) << "\t" << ANS << "\t" << clustercount << "\t" << inverseclustercount << endl;
cerr << word << " , ";
}
cerr << endl;
// Write out parameters.
global << "OutputDir\tContextSize\tWeightingSheme\tWinBehind\tWinAhead\tSeparate\tPercentToSample\tMetric\tNormalization\tThreshold" << endl;
global << outputloc.first << "\t" << context_size << "\t" << weightingScheme << "\t" << windowLenBehind << "\t" << windowLenAhead << "\t";
global << separate << "\t" << percenttosample << "\t";
global << metric << "\t" << normalization;
if (usezscore) {
global << threshold << endl;
} else {
global << endl;
}
// cerr << "Time is: " << timestamp() << endl;
ans.close();
global.close();
// delete [] neighbours, vectors;
// cerr << "Trying to delete GCM in memory....." << endl;
for(size_t i = 0; i < _numwords; i++)
if(vectors[i] != NULL)
delete [] vectors[i];
cerr << "Success. Finished processing all words' neighborhoods at " << timestamp() << endl;
return 0;
}
int SDDB::printVects(istream &in,
const int context_size,
int weightingScheme,
const int windowLenBehind, const int windowLenAhead,
const int wordlistsize,
const int separate, const string outputpath, const string normalization,
const int saveGCM
)
{
int words_to_print = 0;
int behind = min(windowLenBehind, _realBehind);
int ahead = min(windowLenAhead, _realAhead);
int windowLen = behind+ahead;
// corpus size per million
Float PerMillionDivisor = static_cast<Float>(_corpussize)/1000000.0;
cerr << "Corpus size / 1000000 = " << PerMillionDivisor << endl;
//size_t num_dimensions = 0;
// get all words from lexicon, put them in array of strings.
idMap words;
words = _idMap;
// create the directories
pair<string,string> outputloc = createDirectories(outputpath,0);
// collect all of the words we'll be printing distances for
cerr << "Time is: " << timestamp() << endl;
cerr << "Reading in words of interest" << endl;
vector<resultdata> results;
//load words
LoadWords(in, wordlistsize, results,_normCase);
cerr << "Read " << results.size() << " lines." << endl;
vector<resultdata> finalresults;
//Dictionary *words_of_interest = dictNew(50000);
Dictionary words_of_interest;
// Find words that are not in our lexicon from word list.
vector<resultdata>::iterator results_iter;
for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
string key = (*results_iter).word;
if ( _dict.find(key) != _dict.end()) {
if (_frequency[_dict[key]] > 0) {