-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpgrk9169.java
321 lines (267 loc) · 7.25 KB
/
pgrk9169.java
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
//Kaushil Ruparelia CS610 9169 prp
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @author kaushilruparelia
*
*/
public class pgrk9169 {
private static List<ArrayList<Integer>> adjacencyList;
private static double[] pageRank;
private static double[] contribution;
private static double[] old_pageRank;
private static int nodeCount;
private static int edgeCount;
private static int iterations;
private static final double dampingFactor = 0.85;
private static double offset = 0;
/**
* @param args
*/
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Please enter valid command line argument!!!");
return;
}
//Read the arguments
String filename = args[2];
int initialValue = Integer.parseInt(args[1]);
iterations = Integer.parseInt(args[0]);
//Get the input
String input = "";
try {
input = readFile(filename);
} catch (IOException e) {
// Auto-generated catch block
System.out.println("Could not read the file!");
e.printStackTrace();
return;
}
//Split the input as rows of nodes
String[] rows = input.split("\n");
//Check the boundary condition
if (rows.length < 2) {
System.out.println("Invalid input");
return;
}
try {
//Get the header row and its details
int[] headerArray = extractNodeValues(rows[0]);
//Get the number of nodes and edges
nodeCount = headerArray[0];
edgeCount = headerArray[1];
if (edgeCount < rows.length -1) {
System.out.println("Inconsistent data!");
return;
}
if (nodeCount > 10) {
iterations = 0;
initialValue = -1;
}
//Initialize Variables
initializeVariables(initialValue);
//Create adjacency List
createAdjacencyList(rows);
//Calculate the contribution
calculateContribution();
int count =0;
printPageRank(count);
//Loop until the values converge
do {
//Calculate the page rank
calculatePageRank();
++count;
//Print the page rank
if (nodeCount <= 10) {
printPageRank(count);
}
} while (!didConverge(count));
if (nodeCount > 10) {
printPageRankForHigherNodes(count);
}
} catch (Exception e) {
// Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Reads a file and returns a Strings Array
* @param filePath
* @return
* @throws IOException
*/
public static String readFile(String filePath) throws IOException {
Path path = Paths.get(filePath);
List<String> inputFileList = Files.readAllLines(path, StandardCharsets.US_ASCII);
String inputString = "";
for (String string : inputFileList) {
inputString = inputString.concat(string) + "\n";
}
return inputString;
}
/**
* Initializes the adjacencyList, hub and authority
* @param initialValue
*/
public static void initializeVariables(int initialValue) {
// Initialize the values
adjacencyList = new ArrayList<ArrayList<Integer>>(nodeCount);
pageRank = new double[nodeCount];
contribution = new double[nodeCount];
old_pageRank= new double[nodeCount];
offset = (1 - dampingFactor)/nodeCount;
double init = 0;
switch (initialValue) {
case 0:
case 1:
init = initialValue;
break;
case -1:
init = 1 / (double)nodeCount;
break;
case -2:
init = 1 / Math.sqrt(nodeCount);
break;
default:
init = initialValue;
break;
}
for (int i = 0; i < nodeCount; i++) {
adjacencyList.add(new ArrayList<>());
pageRank[i] = init;
old_pageRank[i] = init;
}
}
/**
* Creates an adjacency list from the input.
* @param rows
* @throws Exception
*/
public static void createAdjacencyList(String[] rows) throws Exception {
//Create an adjacency list of the edges
int[] row;
int node1, node2;
for (int index = 1; index <= edgeCount; index++) {
row = extractNodeValues(rows[index]);
node1 = row[0];
node2 = row[1];
if (node1 >= nodeCount || node2 >= nodeCount) {
System.out.println("Invalid input in rows 2: "+node1+" "+node2+ " "+ adjacencyList.size());
return;
}
adjacencyList.get(node1).add(node2);
}
}
/**
* Prints the adjacency list.
*/
public static void printAdjacencyList() {
for (List<Integer> list : adjacencyList) {
for (Integer integer : list) {
System.out.print(integer + " ");
}
System.out.println();
}
}
/**
* Extracts the Node Values
* @param line
* @return An array of integers with 2 values.
* @throws Exception
*/
public static int[] extractNodeValues(String line) throws Exception {
String []row = line.split(" ");
if (row.length != 2) {
throw new Exception("Invalid Input found in row:"+row);
}
int[] result = new int[2];
result[0] = Integer.parseInt(row[0]);
result[1] = Integer.parseInt(row[1]);
return result;
}
/**
* Calculate the Contribution or the out degree
*/
public static void calculateContribution() {
for (int i = 0; i < contribution.length; i++) {
contribution[i] = adjacencyList.get(i).size();
}
}
/**
* Calculate the page rank
*/
public static void calculatePageRank() {
double[] newPageRankArray = new double[nodeCount];
double intermediateCalculation;
for (int i = 0; i < pageRank.length; i++) {
intermediateCalculation = 0;
for (int j = 0; j < adjacencyList.size(); j++) {
if (adjacencyList.get(j).contains(i)) {
intermediateCalculation += pageRank[j] / contribution[j];
}
}
newPageRankArray[i] = offset + dampingFactor * intermediateCalculation;
}
old_pageRank = pageRank;
pageRank = newPageRankArray;
}
/**
* Check if the values of page rank converged
* @return True if the converge is successful
*/
public static boolean didConverge(int current_iteration) {
double multiplicationFactor = 0;
if (iterations > 0) {
return current_iteration == iterations;
}
else {
if (iterations == 0) {
multiplicationFactor = 100000;
}
else {
multiplicationFactor = Math.pow(10, (iterations * -1));
}
for (int i = 0; i < pageRank.length; i++) {
if ((int)Math.floor(pageRank[i]*multiplicationFactor) != (int)Math.floor(old_pageRank[i]*multiplicationFactor)) {
return false;
}
}
return true;
}
}
/**
* Print the Page Rank Values
*/
public static void printPageRank(int iteration) {
if (iteration == 0) {
System.out.print("Base : "+ iteration + " : ");
}
else {
System.out.print("Iterat : "+ iteration + " : ");
}
DecimalFormat numberFormat = new DecimalFormat("0.0000000");
for (int i = 0; i < pageRank.length; i++) {
System.out.print("PR["+ i + "] = "+numberFormat.format(pageRank[i]) + " ");
}
System.out.println();
}
/**
* Prints the Pagerank if higher than 10 nodes.
* @param iteration
*/
public static void printPageRankForHigherNodes(int iteration) {
System.out.println("Iterat : "+ iteration + " : ");
DecimalFormat numberFormat = new DecimalFormat("0.0000000");
for (int i = 0; i < pageRank.length; i++) {
System.out.println("PR["+ i + "] = "+numberFormat.format(pageRank[i]) + " ");
}
System.out.println();
}
}