-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPageRankAlgorithm.php
90 lines (70 loc) · 2.62 KB
/
PageRankAlgorithm.php
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
<?php
declare(strict_types=1);
namespace PhpScience\PageRank\Service;
use PhpScience\PageRank\Data\NodeCollectionInterface;
use PhpScience\PageRank\Service\PageRankAlgorithm\NormalizerInterface;
use PhpScience\PageRank\Service\PageRankAlgorithm\RankingInterface;
use PhpScience\PageRank\Strategy\NodeDataSourceStrategyInterface;
class PageRankAlgorithm implements PageRankAlgorithmInterface
{
private NodeDataSourceStrategyInterface $nodeDataStrategy;
private RankingInterface $ranking;
private NormalizerInterface $normalizer;
public function __construct(
RankingInterface $ranking,
NodeDataSourceStrategyInterface $nodeDataStrategy,
NormalizerInterface $normalizer
) {
$this->nodeDataStrategy = $nodeDataStrategy;
$this->ranking = $ranking;
$this->normalizer = $normalizer;
}
public function run(int $maxIterate): NodeCollectionInterface
{
$this->initiateRanking();
$this->runBatch($maxIterate);
return $this->normalize();
}
public function initiateRanking(): NodeCollectionInterface
{
$nodeCollection = $this->nodeDataStrategy->getNodeCollection();
$this->ranking->calculateInitialRank($nodeCollection);
$this->nodeDataStrategy->updateNodes($nodeCollection);
return $nodeCollection;
}
public function runBatch(int $maxIterate): NodeCollectionInterface
{
$nodeCollection = $this->nodeDataStrategy->getNodeCollection();
$this->powerIterate($nodeCollection, $maxIterate);
return $nodeCollection;
}
public function normalize(): NodeCollectionInterface
{
$nodeCollection = $this->nodeDataStrategy->getNodeCollection();
$min = $this->nodeDataStrategy->getLowestRank();
$max = $this->nodeDataStrategy->getHighestRank();
$this->normalizer->normalize(
$nodeCollection,
$min,
$max
);
return $nodeCollection;
}
private function powerIterate(
NodeCollectionInterface $nodeCollection,
int $maxIterate
): void {
$noneRepresentableDiffCount = 0;
$i = 0;
while (
$i < $maxIterate
&& $noneRepresentableDiffCount < $nodeCollection->getAllNodeCount()
) {
$i++;
$noneRepresentableDiffCount = $this
->ranking
->calculateRankPerIteration($nodeCollection);
$this->nodeDataStrategy->updateNodes($nodeCollection);
}
}
}