-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutilities.cpp
1268 lines (1124 loc) · 35.4 KB
/
utilities.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 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/>.
*/
#define _LARGE_FILES 1
// Utility functions for HIDEX
// ****************************************************************************
//
// ****************************************************************************
#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 <errno.h>
#include "SDDB.h"
#include "Exception.h"
#include "Filesystem.h"
#include "utilities.h"
#include "string.h"
#include <unistd.h>
#include <unistr.h>
#include <uninorm.h>
#include <unitypes.h>
#include <unictype.h>
#include <unistdio.h>
#include <unicase.h>
bool
//
// Extracts the next word from the input stream. This function has the same
// functionality as "cin >> word", excepts it additionally makes sure that
// the word buffer is not over-run!
//
getWord(istream& in, string& word)
{
int i = 0;
char ch;
word = "";
while(in.get(ch))
{
if(!isspace(ch)) {
if(i > MAX_WORDLEN) {
in.putback(ch);
break;
} else {
word += ch;
i++;
}
}
else {
break;
}
}
if (i > 0)
return true;
else
return false;
}
void
//
// Copy the file at source, to dest... Not currently used.
//
copy_file(const char *source, const char *dest) {
ifstream in(source);
ofstream out(dest);
char ch;
while(in.get(ch))
out << ch;
in.close();
out.close();
}
void
// Loads pairs of words to find distances for.
LoadPairs(istream& in, vector<pairdata> &results, const bool normCase) {
pairdata temp;
cerr << "Reading in pairs from wordlist" << endl;
string lang = getLang();
while (!in.eof()){
if (in.fail()) {
throw Exception("Error Reading Input File.. Make sure it is in the correct format. Exiting\n");
}
string tempstring1 = "";
string tempstring2 = "";
in >> tempstring1 >> tempstring2;
if (tempstring1 == "---END.OF.DOCUMENT---")
break;
if ((tempstring1.length() > MAX_WORDLEN) || (tempstring2.length() > MAX_WORDLEN)) {
throw Exception("A Word was too long. Exiting\n");
}
if (normCase) {
temp.word1 = downstring(tempstring1,lang);
temp.word2 = downstring(tempstring2,lang);
} else {
temp.word1 = tempstring1;
temp.word2 = tempstring2;
}
temp.distance = 0.0;
results.push_back(temp);
}
}
// void
// //
// // Loadwords: loads a file with target words for similarity measurements.
// // Will generate a random subsample if desired.
// //
// //
// LoadWordsOld(istream& in, const int wordlistsize, vector<resultdata> &results, const bool normCase) {
// resultdata temp;
// vector<resultdata> wordlist;
// // bool done_reading_file = false;
// // cerr << "Reading in words from wordlist" << endl;
// string lang = getLang();
// while (!in.eof()){
// if (in.fail()) {
// throw Exception("Error Reading Input File.. Make sure it is in the correct format. Exiting\n");
// }
// string tempstring = "";
// Float tempdouble = 0.0;
// in >> tempstring;
// if (tempstring == "---END.OF.DOCUMENT---")
// break;
// if (tempstring.length() > MAX_WORDLEN) {
// throw Exception("Maximum Word Length was exceeded in your word list input file. Exiting");
// }
// temp.ANS = 10000000;
// temp.InverseNcount = 0.0;
// if (normCase) {
// temp.word = downstring(tempstring,lang);
// } else {
// temp.word = tempstring;
// }
// temp.LDRT = tempdouble;
// wordlist.push_back(temp);
// }
// unsigned int numwords = wordlist.size();
// cerr << "Got " << numwords << " from word list. " << endl ;
// if ( numwords< (unsigned int)wordlistsize) {
// results = wordlist;
// } else {
// cerr << " Only " << wordlistsize << " were desired. " << endl;
// cerr << "Generating random subsample of words." << endl;
// // Create subsample
// int seed = time(0);
// unsigned int randomnumber;
// srand(seed);
// set<int> wordset;
// vector<resultdata> subsamplewordlist;
// int i;
// // Generate random set of unique indicies
// for (i = 0; wordset.size() < (unsigned int)wordlistsize; i++) {
// randomnumber = (unsigned int)(rand() % numwords);
// wordset.insert(randomnumber);
// // cerr << randomnumber << " " << i <<endl;
// }
// // copy random words into new vector
// set<int>::iterator iter;
// cerr << endl << "Picked: ";
// for (iter = wordset.begin(); iter != wordset.end(); iter++) {
// subsamplewordlist.push_back(wordlist[*iter]);
// // cerr << *iter << endl;
// }
// results = subsamplewordlist;
// }
// }
void
//
// Loadwords: loads a file with target words for similarity measurements.
// Will generate a random subsample if desired.
//
//
LoadWords(istream& in, const int wordlistsize, vector<resultdata> &results, const bool normCase) {
resultdata temp;
vector<resultdata> wordlist;
// bool done_reading_file = false;
// cerr << "Reading in words from wordlist" << endl;
string lang = getLang();
string tempstring = "";
while (in >> tempstring) {
Float tempdouble = 0.0;
if (tempstring.length() > MAX_WORDLEN) {
cerr << "Yikes!!! This word was too long: " << tempstring << endl;
throw Exception("Maximum Word Length was exceeded in your word list input file. Please remove it and try again.");
}
temp.ANS = 10000000;
temp.InverseNcount = 0.0;
if (normCase) {
temp.word = downstring(tempstring,lang);
} else {
temp.word = tempstring;
}
temp.LDRT = tempdouble;
wordlist.push_back(temp);
if (in.fail()) {
throw Exception("Error Reading Input File.. Not sure what went wrong!\n");
}
}
unsigned int numwords = wordlist.size();
cerr << "Got " << numwords << " from word list. " << endl ;
if ( numwords< (unsigned int)wordlistsize) {
results = wordlist;
} else {
cerr << " Only " << wordlistsize << " were desired. " << endl;
cerr << "Generating random subsample of words." << endl;
// Create subsample
int seed = time(0);
unsigned int randomnumber;
srand(seed);
set<int> wordset;
vector<resultdata> subsamplewordlist;
int i;
// Generate random set of unique indicies
for (i = 0; wordset.size() < (unsigned int)wordlistsize; i++) {
randomnumber = (unsigned int)(rand() % numwords);
wordset.insert(randomnumber);
// cerr << randomnumber << " " << i <<endl;
}
// copy random words into new vector
set<int>::iterator iter;
cerr << endl << "Picked: ";
for (iter = wordset.begin(); iter != wordset.end(); iter++) {
subsamplewordlist.push_back(wordlist[*iter]);
// cerr << *iter << endl;
}
results = subsamplewordlist;
}
}
void addtoresults(vector<resultdata> &results, string word, Float ANS, Float InverseNcount)
{
// Add distance data to results vector for later correlation
vector<resultdata>::iterator results_iter;
for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
if ((*results_iter).word == word) {
(*results_iter).ANS = ANS;
(*results_iter).InverseNcount = InverseNcount;
break;
}
}
}
std::string getcorrelation(vector<resultdata> &results) {
char buffer[128];
vector<resultdata>::iterator results_iter;
Float size = static_cast<Float>(results.size());
// sum of scores, sum of squared scores sss
Float sumANS = 0.0;
Float sssANS = 0.0;
Float sumNcount = 0.0;
Float sssNcount = 0.0;
Float sumLDRT = 0.0;
Float sssLDRT = 0.0;
Float sumprodAL = 0.0;
Float sumprodNL = 0.0;
Float sign = 1.0;
// calculate all the sums.
for (results_iter=results.begin(); results_iter != results.end(); results_iter++) {
sumANS += (*results_iter).ANS ;
sssANS += (*results_iter).ANS * (*results_iter).ANS;
sumNcount += (*results_iter).InverseNcount;
sssNcount += (*results_iter).InverseNcount * (*results_iter).InverseNcount;
sumLDRT += (*results_iter).LDRT ;
sssLDRT += (*results_iter).LDRT * (*results_iter).LDRT ;
sumprodAL += (*results_iter).ANS * (*results_iter).LDRT ;
sumprodNL += (*results_iter).InverseNcount * (*results_iter).LDRT ;
}
// calculate corr btween ANS and LDRT
Float numeratorAL = 0.0;
Float denominatorAL = 0.0;
numeratorAL = (size * sumprodAL ) - (sumANS * sumLDRT);
if (numeratorAL < 0)
sign = -1.0;
numeratorAL *= numeratorAL;
denominatorAL = ((size * sssANS) - (sumANS * sumANS)) * ((size * sssLDRT) - (sumLDRT * sumLDRT));
Float r2AL = numeratorAL / denominatorAL;
Float rAL = sqrt(r2AL) * sign;
//reset sign
sign = 1.0;
// calculate corr btween Ncount and LDRT
Float numeratorNL = 0.0;
Float denominatorNL = 0.0;
numeratorNL = (size * sumprodNL ) - (sumNcount * sumLDRT);
if (numeratorNL < 0)
sign = -1.0;
numeratorNL *= numeratorNL;
denominatorNL = ((size * sssNcount) - (sumNcount * sumNcount)) * ((size * sssLDRT) - (sumLDRT * sumLDRT));
Float r2NL = numeratorNL / denominatorNL;
Float rNL = sqrt(r2NL) * sign;
string reply = "";
// string reply = "The correlation between ANS and LDRT: r2 = ";
sprintf(buffer,"%.4f\t%.4f\t%.4f\t%.4f", r2AL, rAL, r2NL, rNL);
reply += buffer;
// reply += "The correlation between Ncount and LDRT: r2 = ";
// sprintf(buffer,"%.8f r = %.8f\n", r2NL, rNL);
// reply += buffer;
return reply;
}
//
// Sort the elements of pairs[] by their value (ascending order).
// If two words have the same value, resolve ties by which
// words' letters come first in the alphabet
//
// Now uses qsort.
// int compare (const void * a, const void * b)
// {
// return ( ((const DictPair*)b)->value - ((const DictPair*)a)->value );
// }
// void value_sort2(const DictPair *pairs[], const int size) {
// qsort (pairs, size, sizeof(DictPair*), compare);
// }
// void value_sort(const DictPair *pairs[], const int size)
// {
// for(int i = 0; i < size; i++)
// {
// int lowestValPos = i;
// for(int j = size-1; j > i; j--)
// {
// if(pairs[lowestValPos]->value > pairs[j]->value)
// lowestValPos = j;
// else if(pairs[lowestValPos]->value == pairs[j]->value &&
// strcmp(pairs[lowestValPos]->key, pairs[j]->key) > 0)
// lowestValPos = j;
// }
// if(lowestValPos != i)
// {
// const DictPair *temp = pairs[i];
// pairs[i] = pairs[lowestValPos];
// pairs[lowestValPos] = temp;
// }
// }
// }
void
//
// Reads the contents of the file to the specified dictionary,
// and give each a unique numeric value to use for reference in
// the SDDBAccessors
//
build_starting_dict(Dictionary& D, string filename, FrequencyMap& frequencies, const bool normCase)
{
string word = "";
string lang = getLang();
int i = MIN_WORD_VAL;
cerr << "Case Normalization = " << normCase << endl;
ifstream inStream(filename.c_str());
if (!inStream.good()) {
throw Exception("Dictionary file could not be opened");
} else {
while (inStream >> word) {
if (normCase) {
word = downstring(word,lang);
}
if (D.find(word) != D.end()) {
cerr << "Word, " << word << ", exists in dictionary already... Skipping it." << endl;
continue;
}
D[word] = i;
frequencies[i] = 0;
i++;
}
}
}
void
//
// Builds a dictionary and gives each word an id. Also fills frequencies
// up with the counts of the words
//
build_dict_and_freqs(Dictionary& D, string filename, FrequencyMap& frequencies)
{
ifstream inStream(filename.c_str());
string word;
int id;
int freq;
do {
id = 0;
freq = 0;
inStream >> word;
inStream >> id;
inStream >> freq;
D[word] = id;
frequencies[id] = freq;
} while (inStream);
}
void
//
// Builds a dictionary and gives each word an id. Also fills frequencies
// up with the counts of the words
//
build_variance(string filename, VarianceMap& variances)
{
if (!file_exists(filename)) {
ostringstream message;
message << "Could not open variance file " << filename << " . This could be because you did not create the database using variance mode. Please do a 'remove' then recreate and update the database with useVariance set to 1 in the config file." << endl;
throw Exception(message.str());
}
ifstream inStream(filename.c_str());
string word;
int id;
Float variance;
do {
id = 0;
variance = 0.0;
inStream >> word;
inStream >> id;
inStream >> variance;
variances[id] = variance;
// cerr << "Got Word:" << word << " id:" << id << " Freq:" << freq << endl;
} while (inStream);
}
void build_idMap(Dictionary& D, idMap& words) {
for(Dictionary::iterator i = D.begin(); i != D.end() ; ++i) {
words[i->second] = i->first;
}
}
void
//
// Write a dictionary and the word frequencies to file
//
write_dict_and_freqs(Dictionary& D, string filename, FrequencyMap& frequencies)
{
ofstream out(filename.c_str());
if (out.good())
{
for (Dictionary::iterator i = D.begin(); i != D.end(); i++) {
out << i->first << "\t" << i->second << "\t" << frequencies[i->second] << endl;
}
out.close();
}
else {
throw Exception("WRITE_DICT: Could not write the output file. Exiting");
}
}
void
//
// Write a dictionary and the word frequencies to file
//
write_vars(Dictionary& D, string filename, VarianceMap& frequencies)
{
ofstream out(filename.c_str());
if (out.good())
{
for (Dictionary::iterator i = D.begin(); i != D.end(); i++) {
out << i->first << "\t" << i->second << "\t" << frequencies[i->second] << endl;
}
out.close();
}
else {
throw Exception("WRITE_VARIANCES: Could not write the output file. Exiting");
}
}
void
//
// Write initial zero variances....
//
build_starting_variance(Dictionary& D, string filename)
{
ofstream out(filename.c_str());
if (out.good())
{
for (Dictionary::iterator i = D.begin(); i != D.end(); i++) {
out << i->first << "\t" << i->second << "\t" << 0.0 << endl;
}
out.close();
}
else {
throw Exception("Saving initial Variance file: Could not write the output file. Exiting");
}
}
//
// Sorts an array of type T into ascending order
//
template<class T>
void binary_sort(T array[], int len) {
if(len <= 1)
return;
else if(len == 2) {
if(array[1] > array[0])
return;
else {
T tmp = array[0];
array[0] = array[1];
array[1] = tmp;
return;
}
}
else {
T arr1[len/2];
T arr2[len - (len/2)];
int i;
for(i = 0; i < len/2; i++)
arr1[i] = array[i];
for(; i < len; i++)
arr2[i - (len/2)] = array[i];
binary_sort(arr1, len/2);
binary_sort(arr2, (len - len/2));
int j;
for(i = j = 0; i < len/2 && j < (len - len/2);) {
if(arr1[i] < arr2[j]) {
array[i+j] = arr1[i];
i++;
}
else {
array[i+j] = arr2[j];
j++;
}
}
for(; j < (len - len/2); j++)
array[i+j] = arr2[j];
for(; i < len/2; i++)
array[i+j] = arr1[i];
}
}
//
// returns the place in the array the element exists
// at. returns len if the element does not exist
//
template<class T>
int array_place(T *array, T elem, int len) {
int i;
for(i = 0; i < len; i++)
if(array[i] == elem)
return true;
return i;
}
void wait ( size_t seconds ) {
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
string
// TimeStamper
timestamp () {
time_t rawtime;
int month;
int year;
struct tm * tinfo;
stringstream tstamp;
time( &rawtime );
tinfo = localtime (&rawtime);
month = tinfo->tm_mon + 1;
year = tinfo->tm_year + 1900;
tstamp << setfill('0');
tstamp << year << "." << setw(2) << month << "." << setw(2) << tinfo->tm_mday << "."
<< setw(2) <<tinfo->tm_hour << "." << setw(2) << tinfo->tm_min << "." << setw(2) << tinfo->tm_sec;
return tstamp.str();
}
/**
* C++ version std::string style "itoa":
*/
std::string itoa(int value, unsigned int base) {
const char digitMap[] = "0123456789abcdef";
std::string buf;
// Guard:
if (base == 0 || base > 16) {
// Error: may add more trace/log output here
return buf;
}
// Take care negative int:
std::string sign;
int _value = value;
if (value < 0) {
_value = -value;
sign = "-";
}
// Translating number to string with base:
for (int i = 30; _value && i ; --i) {
buf = digitMap[ _value % base ] + buf;
_value /= base;
}
return sign.append(buf);
}
/////
void add_smallest(word_distance_pair *entries, int len, int id, Float distance)
{
// add the smallest distance values to the neighbor list.
// does mini-sort
for(int i = 0; i < len; i++) {
if(entries[i].id == -1 || distance < entries[i].distance) {
for(int j = len-1; j > i; j--) {
entries[j].id = entries[j-1].id;
entries[j].distance = entries[j-1].distance;
}
entries[i].id = id;
entries[i].distance = distance;
return;
}
}
}
Float
// Calculate the magnitude of a word vector
get_magnitude(Float *vect, int context_size) {
Float magnitude = 0;
for (int i = 0; i < context_size; i++) {
magnitude += (vect[i] * vect[i]);
}
magnitude = sqrt(magnitude);
return magnitude;
}
void removeDBFiles (const string& dbname, const string& dbpath) {
string dbBase = dbpath + dbname + DBINFO_TAG;
string dictfilename = dbpath + dbname + DICT_TAG;
string datadirname = dbpath + dbname + DBDIR_TAG;
string gcmfilename = dbpath + dbname + GCM_TAG;
string varfilename = dbpath + dbname + VAR_TAG;
bool errorState = false;
cerr << "Removing all relevant files now....Please be patient."<< endl;
if (unlink(dbBase) == 0) {
cerr << "Removed " << dbBase << endl;
} else {
cerr << "Could not remove " << dbBase << ". File does not exist" << endl;
errorState = true;
}
if (unlink(dictfilename) == 0) {
cerr << "Removed " << dictfilename << endl;
} else {
cerr << "Could not remove " << dictfilename << ". File does not exist" << endl;
errorState = true;
}
if (rmdir(datadirname) == 0) {
cerr << "Removed " << datadirname << endl;
} else {
cerr << "Could not remove " << datadirname << ". Directory does not exist" << endl;
errorState = true;
}
if (unlink(varfilename) == 0) {
cerr << "Removed " << varfilename << endl;
} else {
cerr << "Could not remove " << varfilename << ". File does not exist" << endl;
errorState = true;
}
if (unlink(gcmfilename) == 0) {
cerr << "Removed " << gcmfilename << endl;
} else {
cerr << "Could not remove " << gcmfilename << ". File does not exist" << endl;
}
if (errorState) {
cerr << "=====!!!!!!!!!!======\nOops! There were errors detected while deleting the data. They usually be ignored. \nIf you are still having problems, delete the above files and folders manually." << endl;
}
}
bool dbExists (const string& dbname) {
string dictfilename = dbname + DICT_TAG;
string datadirname = dbname + DBDIR_TAG;
if ( file_exists(dbname) || file_exists(dictfilename) || dir_exists(datadirname)) {
cerr << "Found a previous database." << endl;
return true;
} else {
return false;
}
}
bool GCMexists(const string& dbname) {
string GCMfilename = dbname + GCM_TAG;
// string ContextFilename = dbname + CONTEXT_TAG;
// if ( file_exists(GCMfilename) || file_exists(ContextFilename)) {
if ( file_exists(GCMfilename)) {
cerr << "Found a GCM file." << endl;
return true;
} else {
cerr << "Did not find a GCM file." << endl;
return false;
}
}
bool dbReady (const string& dbname, const string& dbpath ) {
string dictfilename = dbpath + dbname + DICT_TAG;
string datadirname = dbpath + dbname + DBDIR_TAG;
string dbinfofilename = dbpath + dbname + DBINFO_TAG;
if ( file_exists(dbinfofilename) && file_exists(dictfilename) && dir_exists(datadirname)) {
return true;
} else {
cerr << "Database is not ready. One of these files/directories are missing: \n" << dbinfofilename << endl << dictfilename << endl << datadirname << endl;
return false;
}
}
int makeDir (const string& dirName) {
if (mkdir(dirName, 0755) >= 0) {
cerr << "Created directory " << dirName << endl;
return 0;
}
else {
ostringstream message;
message << "Could not create directory " << dirName << " : " << strerror(errno) << " .. Aborting! " << endl;
throw Exception(message.str());
}
}
// void removeDBFiles (const string& dbname, const string& dbpath) {
// string dbBase = dbpath + dbname;
// string dictfilename = dbpath + dbname + ".dict";
// bool errorState = false;
// unsigned long fileCount = 0;
// string datadirname = dbpath + dbname + ".data";
// cerr << "Removing database now....Please be patient."<< endl;
// fs::path dbFile( dbBase);
// fs::path dictLoc( dictfilename);
// fs::path dataLoc( datadirname);
// if (fs::remove(dbFile)) {
// cerr << "Removed " << dbFile.string() << endl;
// } else {
// cerr << "Could not remove " << dbFile.string() << ". File does not exist" << endl;
// errorState = true;
// }
// if (fs::remove(dictLoc)) {
// cerr << "Removed " << dictLoc.string() << endl;
// } else {
// cerr << "Could not remove " << dictLoc.string() << ". File does not exist" << endl;
// errorState = true;
// }
// fileCount = fs::remove_all(dataLoc);
// if (fileCount > 0) {
// cerr << "Removed " << dataLoc.string() << ", " << fileCount << " files." << endl;
// } else {
// cerr << "Could not remove " << dataLoc.string() << ". Directory does not exist" << endl;
// errorState = true;
// }
// if (errorState) {
// throw Exception("There were errors detected. Database was not able to be removed.");
// }
// }
// bool dbExists (const string& dbname) {
// bool test1, test2, test3;
// string dictfilename = dbname + ".dict";
// string datadirname = dbname + ".data";
// // fs::path dbFile( fs::initial_path() / dbname);
// // fs::path dictFile( fs::initial_path() / dictfilename);
// // fs::path dataLoc( fs::initial_path() / "data");
// test1=false;
// test2=false;
// test3=false;
// try {
// fs::path dbFile(dbname);
// test1 = fs::exists( dbFile );
// }
// catch(std::exception const& e) {}
// catch(...) {
// std::cout << "whoops!" << std::endl;
// }
// try {
// fs::path dataLoc(datadirname);
// test2 = fs::exists( dataLoc );
// }
// catch(std::exception const& e) {}
// catch(...) {
// std::cout << "whoops!" << std::endl;
// }
// try {
// fs::path dictFile(dictfilename);
// test3 = fs::exists(dictFile);
// }
// catch(std::exception const& e) {}
// catch(...) {
// std::cout << "whoops!" << std::endl;
// }
// if (test1 || test2 || test3) {
// return true;
// } else {
// return false;
// }
// }
// void makeDir (const string& dirName) {
// // fs::path dirLoc( fs::initial_path() / dirName);
// fs::path dirLoc( dirName);
// if (fs::create_directory (dirLoc)) {
// cerr << "Created directory " << dirLoc.string() << endl;
// } else {
// cerr << "Did not create directory " << dirLoc.string() << " as it already existed." << endl;
// }
// }
void split_words(string text, vector<string> &words, char ws)
{
if (text.length() > 0 && text[0] == ws) {
text.erase(0, text.find_first_not_of(ws));
}
while (text.length() > 0) {
words.push_back(text.substr(0, text.find_first_of(ws)));
text.erase(0, text.find_first_of(ws));
text.erase(0, text.find_first_not_of(ws));
}
}
void ps (string& s){ cout << s << endl; }
void pd (Dictionary& D) {
for (Dictionary::iterator i = D.begin(); i != D.end(); i++) {
cout << i->first << ":" << i->second << " , ";
}
cout << endl;
}
vector<int> createWeightScheme(int windowLen, int behind, int scheme)
{
int ahead = windowLen - behind;
assert(windowLen >= 0);
vector<int> weights(windowLen);
// vector<int> error(1);
// error[0]=0;
if(scheme == SDDB::RAMPED_LINEAR)
{
cerr << "Creating ramped, linear weighting scheme\n";
for(int i = 0; i < behind; i++)
weights[i] = i + 1;
for(int i = behind; i < windowLen; i++)
weights[i] = windowLen - i;
}
else if(scheme == SDDB::RAMPED_QUADRATIC)
{
cerr << "Creating ramped, quadratic weighting scheme\n";
for(int i = 0; i < behind; i++)
weights[i] = (i + 1)*(i + 1);
for(int i = behind; i < windowLen; i++)
weights[i] = (windowLen - i)*(windowLen - i);
}
else if (scheme == SDDB::FORWARD_RAMP)
{
cerr << "Creating forward ramp, flat backwards\n";
for(int i = 0; i < behind; i++)
weights[i] = 1;
for(int i = behind; i < windowLen; i++)
weights[i] = windowLen - i;
}
else if (scheme == SDDB::BACKWARD_RAMP)
{
cerr << "Creating backwards ramp, flat forwards\n";
for(int i = 0; i < behind; i++)
weights[i] = i + 1;
for(int i = behind; i < windowLen; i++)
weights[i] = 1;
}
else if (scheme == SDDB::INVERSE_RAMP)
{
cerr << "Creating inverse ramped linear weighting scheme\n";
for(int i = 0; i < behind; i++)
weights[i] = behind - i;
for(int i = behind; i < windowLen; i++)
weights[i] = ((i - behind) + 1);
}
else if (scheme == SDDB::INVERSE_QUADRATIC)
{
cerr << "Creating inverse quadratic weighting scheme\n";
for(int i = 0; i < behind; i++)
weights[i] = (behind - i) * (behind - i) ;
for(int i = behind; i < windowLen; i++)
weights[i] = ((i - behind) + 1) * ((i - behind) + 1);
}
else if (scheme == SDDB::SECOND_WORD)
{
cerr << "Creating second-word heavy weighting scheme\n";
for(int i = 0; i < windowLen; i++)
weights[i] = 1;
if (ahead > 2)
weights[windowLen - ahead + 1] = 10;
if (behind > 2)
weights[windowLen - ahead - 2] = 10;
}
else if (scheme == SDDB::THIRD_WORD)
{
cerr << "Creating third-word heavy weighting scheme\n";
for(int i = 0; i < windowLen; i++)
weights[i] = 1;
if (ahead > 3)
weights[windowLen - ahead + 2] = 10;
if (behind > 3)
weights[windowLen - ahead - 3] = 10;
}
else if (scheme == SDDB::FOURTH_WORD)
{
cerr << "Creating third-word heavy weighting scheme\n";
for(int i = 0; i < windowLen; i++)
weights[i] = 1;
if (ahead > 4)
weights[windowLen - ahead + 3] = 10;