1
|
|
|
<?php
|
2
|
|
|
|
3
|
|
|
declare(strict_types=1);
|
4
|
|
|
|
5
|
|
|
namespace PhpScience\PageRank\Service\PageRankAlgorithm;
|
6
|
|
|
|
7
|
|
|
use PhpScience\PageRank\Data\NodeCollectionInterface;
|
8
|
|
|
use PhpScience\PageRank\Strategy\NodeDataSourceStrategyInterface;
|
9
|
|
|
|
10
|
1 |
|
class Ranking implements RankingInterface
|
11
|
|
|
{
|
12
|
|
|
private NodeDataSourceStrategyInterface $nodeDataStrategy;
|
13
|
|
|
private RankComparatorInterface $rankComparator;
|
14
|
|
|
|
15
|
6 |
|
public function __construct(
|
16
|
|
|
RankComparatorInterface $rankComparator,
|
17
|
|
|
NodeDataSourceStrategyInterface $nodeDataStrategy
|
18
|
|
|
) {
|
19
|
6 |
|
$this->nodeDataStrategy = $nodeDataStrategy;
|
20
|
6 |
|
$this->rankComparator = $rankComparator;
|
21
|
6 |
|
}
|
22
|
|
|
|
23
|
3 |
|
public function calculateInitialRank(
|
24
|
|
|
NodeCollectionInterface $nodeCollection
|
25
|
|
|
): void {
|
26
|
3 |
|
foreach ($nodeCollection->getNodes() as $item) {
|
27
|
3 |
|
$item->setRank(1 / $nodeCollection->getAllNodeCount());
|
28
|
|
|
}
|
29
|
3 |
|
}
|
30
|
|
|
|
31
|
5 |
|
public function calculateRankPerIteration(
|
32
|
|
|
NodeCollectionInterface $nodeCollection
|
33
|
|
|
): int {
|
34
|
5 |
|
$nonRepresentableDifference = 0;
|
35
|
|
|
|
36
|
5 |
|
foreach ($nodeCollection->getNodes() as $node) {
|
37
|
5 |
|
$rank = $this->calculateRank($node->getId());
|
38
|
5 |
|
$node->setRank($rank);
|
39
|
|
|
|
40
|
5 |
|
$isEqual = $this->rankComparator->isEqual(
|
41
|
5 |
|
$this->nodeDataStrategy->getPreviousRank($node->getId()),
|
42
|
5 |
|
$node->getRank()
|
43
|
|
|
);
|
44
|
|
|
|
45
|
5 |
|
if ($isEqual) {
|
46
|
4 |
|
$nonRepresentableDifference++;
|
47
|
|
|
}
|
48
|
|
|
}
|
49
|
|
|
|
50
|
5 |
|
return $nonRepresentableDifference;
|
51
|
|
|
}
|
52
|
|
|
|
53
|
5 |
|
private function calculateRank(int $nodeId): float
|
54
|
|
|
{
|
55
|
5 |
|
$rank = .0;
|
56
|
|
|
|
57
|
|
|
$incomingNodeIds = $this
|
58
|
5 |
|
->nodeDataStrategy
|
59
|
5 |
|
->getIncomingNodeIds($nodeId);
|
60
|
|
|
|
61
|
5 |
|
foreach ($incomingNodeIds as $incomingNodeId) {
|
62
|
|
|
$incomingNodePreviousRank = $this
|
63
|
5 |
|
->nodeDataStrategy
|
64
|
5 |
|
->getPreviousRank($incomingNodeId);
|
65
|
|
|
|
66
|
|
|
$countOutgoingNodesOfIncomingNode = $this
|
67
|
5 |
|
->nodeDataStrategy
|
68
|
5 |
|
->countOutgoingNodes($incomingNodeId);
|
69
|
|
|
|
70
|
5 |
|
if (0 === $countOutgoingNodesOfIncomingNode) {
|
71
|
2 |
|
continue;
|
72
|
|
|
}
|
73
|
|
|
|
74
|
|
|
$rank += $incomingNodePreviousRank
|
75
|
3 |
|
/ $countOutgoingNodesOfIncomingNode;
|
76
|
|
|
}
|
77
|
|
|
|
78
|
5 |
|
return $rank;
|
79
|
|
|
}
|
80
|
|
|
}
|
81
|
|
|
|