-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.cpp
More file actions
577 lines (502 loc) · 17.2 KB
/
search.cpp
File metadata and controls
577 lines (502 loc) · 17.2 KB
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
#include "webpage.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <map>
#include <vector>
#include <iostream>
using namespace std;
// Read in the config file and initialize parameters
void readConfig (ifstream& config, ifstream& index, ifstream& query, ofstream& output, double& epsilon, int& steps) {
// Iterate through the config file
string line;
while (getline(config, line)) {
// Ignore comments
if (line.find("#") != string::npos) {
line.erase(line.find('#'));
}
// Replace '=' with whitespace
if (line.find("=") != string::npos) {
replace(line.begin(), line.end(), '=', ' ');
}
stringstream ss(line);
string str;
// Iterate through line
while (ss >> str) {
// Parse config parameters
if (str == "INDEX_FILE") {
string fileName;
ss >> fileName;
index.open(fileName);
} else if (str == "QUERY_FILE") {
string fileName;
ss >> fileName;
query.open(fileName);
} else if (str == "OUTPUT_FILE") {
string fileName;
ss >> fileName;
output.open(fileName);
} else if (str == "RESTART_PROBABILITY") {
ss >> epsilon;
} else if (str == "STEP_NUMBER") {
ss >> steps;
}
}
}
}
// Read in index files
void readIndex (ifstream &index, set<WebPage*> &webPages) {
string fileName;
// Parse through index file
while (getline(index, fileName)) {
if (fileName != "") {
// Create new WebPage
WebPage* webPage = new WebPage(fileName);
webPages.insert(webPage);
}
}
}
// Parse webpage contents
void parseWebPages (set<WebPage*> &webPages, map<string, set<WebPage*> > &mapWordToPage) {
// Iterate through WebPages
for (set<WebPage*>::iterator it = webPages.begin(); it != webPages.end(); it++) {
WebPage* page = *it;
ifstream input(page->getName());
string line;
// Loop through WebPage content line-by-line
while (getline(input, line)) {
string word;
string fileLink;
bool link = false;
// Check for valid characters
for (unsigned int i = 0; i < line.length(); i++) {
// Parsing an outgoing WebPage link
if (link) {
// End of link
if (line[i] == ')') {
// Add outgoing link to current page
page->addOutgoingLink(fileLink);
// Add incoming link to linked page
for (set<WebPage*>::iterator iter = webPages.begin(); iter != webPages.end(); iter++) {
WebPage* linkPage = *iter;
if (linkPage->getName() == fileLink) {
linkPage->addIncomingLink(page->getName());
}
}
link = false;
fileLink = "";
} else {
fileLink += line[i];
}
} else {
// Parse WebPage words
if ((line[i] >= 48 && line[i] <= 57)
|| (line[i] >= 65 && line[i] <= 90)
|| (line[i] >= 97 && line[i] <= 122)) {
char c = line[i];
c = tolower(c);
word += c;
} else {
if (word != "") {
page->addWord(word);
mapWordToPage[word].insert(page);
word = "";
}
if (line[i] == '(') {
link = true;
}
}
}
}
// Add final word of line if it isn't followed by an invalid character
if (word != "") {
page->addWord(word);
mapWordToPage[word].insert(page);
}
}
}
}
// Print the content of a webpage
void printPage (string &fileName, ofstream &output) {
ifstream input(fileName);
// Check valid fileName
if (input.fail()) {
output << "Invalid query" << endl;
} else {
// Print out file line-by-line, ignoring links
output << fileName << endl;
string line;
while (getline(input, line)) {
bool link = false;
for (unsigned int i = 0; i < line.length(); i++) {
if (link) {
if (line[i] == ')')
link = false;
} else {
if (line[i] == '(')
link = true;
else
output << line[i];
}
}
output << endl;
}
}
}
// Print either the incoming or outgoing links of a webpage
void printLinks (string &fileName, ofstream &output, set<WebPage*> &webPages, string &commandType) {
bool fileExists = false;
// Find specified WebPage
for (set<WebPage*>::iterator it = webPages.begin(); it != webPages.end(); it++) {
WebPage* page = *it;
if (page->getName() == fileName) {
fileExists = true;
// Check Incoming vs Outgoing
if (commandType == "INCOMING")
page->printIncomingLinks(output);
else
page->printOutgoingLinks(output);
break;
}
}
if (!fileExists) {
output << "Invalid query" << endl;
}
}
// Search for webpages containing the specified word
set<WebPage*> searchSingleWord (string &word, map<string, set<WebPage*> > &mapWordToPage) {
// Convert to lowercase
for (unsigned int i = 0; i < word.length(); i++) {
word[i] = tolower(word[i]);
}
// Return map with search word as key and set of all WebPages containing search word as value
map<string, set<WebPage*> >::iterator itWord = mapWordToPage.find(word);
set<WebPage*> wordPages;
if (itWord != mapWordToPage.end()) {
wordPages = itWord->second;
}
return wordPages; // If word isn't found, set returns empty
}
// Returns set of WebPages resulting from intersection operation (AND)
set<WebPage*> intersectWebPage (string& word1, string& word2, stringstream &ss, map<string, set<WebPage*> > &mapWordToPage) {
set<WebPage*> andPages;
// Convert to lowercase
for (unsigned int i = 0; i < word1.length(); i++) {
word1[i] = tolower(word1[i]);
}
for (unsigned int i = 0; i < word2.length(); i++) {
word2[i] = tolower(word2[i]);
}
// Return maps of search term to WebPages of both search words
map<string, set<WebPage*> >::iterator itWord1 = mapWordToPage.find(word1);
map<string, set<WebPage*> >::iterator itWord2 = mapWordToPage.find(word2);
if (itWord1 != mapWordToPage.end() && itWord2 != mapWordToPage.end()) {
set<WebPage*> word1Pages = itWord1->second;
set<WebPage*> word2Pages = itWord2->second;
// intersection returns set of pages with word1 and word2
if (word1Pages.size() <= word2Pages.size()) {
for (set<WebPage*>::iterator it1 = word1Pages.begin(); it1 != word1Pages.end(); it1++) {
WebPage* page = *it1;
set<WebPage*>::iterator it2 = word2Pages.find(page);
if (it2 != word2Pages.end()) {
andPages.insert(page);
}
}
} else {
for (set<WebPage*>::iterator it2 = word2Pages.begin(); it2 != word2Pages.end(); it2++) {
WebPage* page = *it2;
set<WebPage*>::iterator it1 = word1Pages.find(page);
if (it1 != word1Pages.end()) {
andPages.insert(page);
}
}
}
}
string word;
// Perform intersection with andSet and following word sets
while (ss >> word) {
for (unsigned int i = 0; i < word.length(); i++) {
word[i] = tolower(word[i]);
}
map<string, set<WebPage*> >::iterator itWord = mapWordToPage.find(word);
if (itWord != mapWordToPage.end()) {
set<WebPage*> wordPages = itWord->second;
for (set<WebPage*>::iterator itAnd = andPages.begin(); itAnd != andPages.end(); itAnd++) {
WebPage* page = *itAnd;
set<WebPage*>::iterator it = wordPages.find(page);
if (it == wordPages.end()) {
andPages.erase(page);
}
}
} else {
// if the word is not found in any page, there is no intersection whatsoever
for (set<WebPage*>::iterator itAnd = andPages.begin(); itAnd != andPages.end(); itAnd++) {
WebPage* page = *itAnd;
andPages.erase(page);
}
}
}
return andPages;
}
// Returns set of WebPages resulting from union operation (OR)
set<WebPage*> unionWebPage (stringstream &ss, map<string, set<WebPage*> > &mapWordToPage) {
set<WebPage*> orPages;
string word;
while (ss >> word) {
for (unsigned int i = 0; i < word.length(); i++) {
word[i] = tolower(word[i]);
}
map<string, set<WebPage*> >::iterator itWord = mapWordToPage.find(word);
if (itWord != mapWordToPage.end()) {
set<WebPage*> wordPages = itWord->second;
for (set<WebPage*>::iterator it = wordPages.begin(); it != wordPages.end(); it++) {
WebPage* page = *it;
orPages.insert(page);
}
}
}
return orPages;
}
// Add all incoming and outgoing pages to set of pages that satisfy search query
set<WebPage*> expandCandidateSet (set<WebPage*> &webPages, set<WebPage*> &candidateSet) {
set<WebPage*> expandedCandidateSet = candidateSet;
// Loop through pages that satisfy search query
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
set<string> outgoing = page->getOutgoingLinks();
set<string> incoming = page->getIncomingLinks();
// Loop through outgoing pages
for (set<string>::iterator itOut = outgoing.begin(); itOut != outgoing.end(); itOut++) {
string linkName = *itOut;
for (set<WebPage*>::iterator iter = webPages.begin(); iter != webPages.end(); iter++) {
WebPage* webPage = *iter;
if (webPage->getName() == linkName) {
// Add outgoing pages to candidate set
expandedCandidateSet.insert(webPage);
}
}
}
// Loop through incoming pages
for (set<string>::iterator itInc = incoming.begin(); itInc != incoming.end(); itInc++) {
string linkName = *itInc;
for (set<WebPage*>::iterator iter = webPages.begin(); iter != webPages.end(); iter++) {
WebPage* webPage = *iter;
if (webPage->getName() == linkName) {
// Add incoming pages to candidate set
expandedCandidateSet.insert(webPage);
}
}
}
}
return expandedCandidateSet;
}
// Checks which page has a higher rank
bool comparePageRank (WebPage* page1, WebPage* page2) {
return (page1->getPageRank() > page2->getPageRank());
}
// PageRank algorithm: evaluate link structure of graph and rank each page
void pageRank (set<WebPage*> &candidateSet, double epsilon, int steps) {
// Store webpages in adjacency matrix
int vertexCount = candidateSet.size();
vector<vector<double>> adjMatrix(vertexCount, vector<double>(vertexCount));
// Loop through candidate set and initialize adjacency matrix
int i = 0;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
set<string> outgoing = page->getOutgoingLinks();
adjMatrix[i][i] = 1.0 / (outgoing.size() + 1); // Add self-loop
for (set<string>::iterator itOut = outgoing.begin(); itOut != outgoing.end(); itOut++) {
string linkName = *itOut;
int j = 0;
for (set<WebPage*>::iterator iter = candidateSet.begin(); iter != candidateSet.end(); iter++) {
WebPage* webPage = *iter;
if (webPage->getName() == linkName) {
adjMatrix[j][i] = 1.0 / (outgoing.size() + 1);
}
j++;
}
}
i++;
}
vector<double> pageRanks;
// Initialize pageRanks to 1 / n
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
double pageRank = 1.0 / candidateSet.size();
page->setPageRank(pageRank);
pageRanks.push_back(pageRank);
}
// Calculate PageRank values iteratively with matrix multiplication
for (int t = 1; t <= steps; t++) {
int i = 0;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
double newRank = 0;
for (unsigned int j = 0; j < candidateSet.size(); j++) {
newRank += adjMatrix[i][j] * pageRanks[j];
}
newRank *= (1 - epsilon);
newRank += (epsilon) * (1.0 / candidateSet.size());
page->setPageRank(newRank);
i++;
}
// Store PageRank values for next iteration
i = 0;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
pageRanks[i] = page->getPageRank();
i++;
}
}
}
// Execute the search commands (queries)
void processQueries (ifstream &query, ofstream &output, set<WebPage*> &webPages, map<string, set<WebPage*> > &mapWordToPage, double epsilon, int steps) {
string command;
// Parse search query
while (getline(query, command)) {
if (command != "") {
stringstream ss(command);
string commandType;
ss >> commandType;
// Determine command type
if (ss.peek() != EOF) {
// Display WebPage contents
if (commandType == "PRINT") {
string fileName;
ss >> fileName;
printPage(fileName, output);
// Print incoming or outgoing links of WebPage
} else if (commandType == "INCOMING" || commandType == "OUTGOING") {
string fileName;
ss >> fileName;
printLinks(fileName, output, webPages, commandType);
// Search for WebPages containing both search words
} else if (commandType == "AND") {
string word1;
string word2;
ss >> word1;
// Check if only one word is searched
if (ss.peek() == EOF) {
// Return pages containing single search word
set<WebPage*> wordPages = searchSingleWord(word1, mapWordToPage);
if (wordPages.size() == 0) // There are no pages containing search word
output << "0" << endl;
else {
set<WebPage*> candidateSet = expandCandidateSet(webPages, wordPages);
pageRank(candidateSet, epsilon, steps);
// Sort the candidate set in order of PageRank
vector<WebPage*> sortedPages;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
sortedPages.push_back(page);
}
sort(sortedPages.begin(), sortedPages.end(), comparePageRank);
// Output sorted pages from single word search
output << sortedPages.size() << endl;
for (unsigned int i = 0; i < sortedPages.size(); i++) {
output << sortedPages[i]->getName() << endl;
}
}
} else {
ss >> word2; // Read in second search word
// Return WebPages containing both search words with set intersection
set<WebPage*> andPages = intersectWebPage(word1, word2, ss, mapWordToPage);
set<WebPage*> candidateSet = expandCandidateSet(webPages, andPages);
pageRank(candidateSet, epsilon, steps);
// Sort the candidate set in order of PageRank
vector<WebPage*> sortedPages;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
sortedPages.push_back(page);
}
sort(sortedPages.begin(), sortedPages.end(), comparePageRank);
// Print sorted set of pages resulting from AND command
output << sortedPages.size() << endl;
for (unsigned int i = 0; i < sortedPages.size(); i++) {
output << sortedPages[i]->getName() << endl;
}
}
// Search for WebPages containing at least one of the search words
} else if (commandType == "OR") {
// Return WebPages containing at least one of the search words with set union
set<WebPage*> orPages = unionWebPage(ss, mapWordToPage);
set<WebPage*> candidateSet = expandCandidateSet(webPages, orPages);
pageRank(candidateSet, epsilon, steps);
// Sort the candidate set in order of PageRank
vector<WebPage*> sortedPages;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
sortedPages.push_back(page);
}
sort(sortedPages.begin(), sortedPages.end(), comparePageRank);
// Print sorted set of pages resulting from OR command
output << sortedPages.size() << endl;
for (unsigned int i = 0; i < sortedPages.size(); i++) {
output << sortedPages[i]->getName() << endl;
}
} else {
output << "Invalid query" << endl;
}
} else {
// Search for the single word
set<WebPage*> wordPages = searchSingleWord(command, mapWordToPage);
if (wordPages.size() == 0) // No WebPages contain the search word
output << "0" << endl;
else {
set<WebPage*> candidateSet = expandCandidateSet(webPages, wordPages);
pageRank(candidateSet, epsilon, steps);
// Sort the candidate set in order of PageRank
vector<WebPage*> sortedPages;
for (set<WebPage*>::iterator it = candidateSet.begin(); it != candidateSet.end(); it++) {
WebPage* page = *it;
sortedPages.push_back(page);
}
sort(sortedPages.begin(), sortedPages.end(), comparePageRank);
// Output sorted pages from single word search
output << sortedPages.size() << endl;
for (unsigned int i = 0; i < sortedPages.size(); i++) {
output << sortedPages[i]->getName() << endl;
}
}
}
} else {
output << "Invalid query" << endl;
}
}
}
int main (int argc, char* argv[])
{
ifstream config;
ifstream index;
ifstream query;
ofstream output;
double epsilon;
int steps;
// Check for config file
if (argc < 2)
config.open("config.txt");
else
config.open(argv[1]);
// Check if config file exists
if (config.fail()) {
cerr << "Couldn't open the config file" << endl;
return 1;
}
// Read config file
readConfig(config, index, query, output, epsilon, steps);
set<WebPage*> webPages;
map<string, set<WebPage*> > mapWordToPage;
// Read index file
readIndex(index, webPages);
// Parse WebPage files for links and words
parseWebPages(webPages, mapWordToPage);
// Execute the user's commands and search queries
processQueries(query, output, webPages, mapWordToPage, epsilon, steps);
// Deallocate WebPage memory
for (set<WebPage*>::iterator it = webPages.begin(); it != webPages.end(); it++)
{
WebPage* page = *it;
delete page;
}
return 0;
}