-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-pagerank.py
107 lines (89 loc) · 3.13 KB
/
3-pagerank.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
###### Import ########
from bson.code import Code
from pprint import pprint
from pymongo import MongoClient
###### Variable ######
# MongoDB configuration
server = 'localhost'
port = 27017
database = 'pathfinder'
col = 'pagerank'
# Itération
iteration = 20
graph = [
{ '_id':"A" ,
'value':{'pagerank' : float(1) , 'links': ["B", "C"]}},
{ '_id':"B",
'value':{'pagerank' : float(1) , 'links': ["C"]}},
{ '_id':"C",
'value':{'pagerank' : float(1) , 'links': ["A"]}},
{ '_id':"D",
'value':{'pagerank' : float(1) , 'links': ["C"]}},
]
###### Function ######
def _exit_rank():
print("Fin du programme !!!")
exit(0)
def _print(results, i):
if i+1 != 1 :
print('*'*40 + '\n' + '*'*40 + '\n' + '*'*40)
print(f"Valeur de I = {i+1}")
for result in results.find():
print(result)
def _conMongoDB(server, port, database, column):
# MongoDB
client = MongoClient(server, port)
db = client[database]
collection = db[column]
return collection
def pagerank(graph, map, reduce, col, iteration = 20):
for i in range(iteration):
results = collection.map_reduce(map , reduce, col)
_print(results, i)
_exit_rank()
return 0
###### Program #######
# Connexion à MongoDB
collection = _conMongoDB(server, port, database, col)
# Création de la collection dans MongoDB
try:
collection.insert_many(graph)
except:
pass
map = Code(
"function() { "
" var page = this._id; "
" var pagerank = this.value.pagerank; "
" var links = this.value.links; "
" var rank = pagerank / links.length; "
" links.forEach(function(link) { "
" emit(link, rank); "
" }); "
" emit(page, 0); "
" emit(page, links); "
"} "
)
reduce = Code(
"function(key, values) { "
" var damping = 0.85; "
" var outlink_list = []; "
" var pagerank = 0; "
" values.forEach(function(value) { "
" if (typeof(value) == 'object') { "
" outlink_list = value "
" } else { "
" pagerank += value "
" } "
" }); "
" pagerank = 1 - damping + ( damping * pagerank ); "
" return {'pagerank' : pagerank , 'links': outlink_list};"
"} "
)
# Fonction pour l'exécution du MapReduce sur la collection
pagerank(graph, map, reduce, col)
# Suppression de la collection
collection.drop()
# Sortie du programme
exit(0)