summaryrefslogtreecommitdiff
path: root/vendor/github.com/DavidBelicza/TextRank/v2/rank/ranking.go
blob: 5fd2dfa4c592eb432d080aed3c2005b332a31ccb (plain)
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
package rank

// Calculate function ranking words by the given algorithm implementation.
func Calculate(ranks *Rank, algorithm Algorithm) {
	updateRanks(ranks, algorithm)
}

func updateRanks(ranks *Rank, algorithm Algorithm) {
	for _, word := range ranks.Words {
		weight := algorithm.WeightingHits(word.ID, ranks)
		word.Weight = weight

		if ranks.Max < word.Weight {
			ranks.Max = word.Weight
		}

		if ranks.Min > word.Weight || ranks.Min == 0 {
			ranks.Min = word.Weight
		}
	}

	for _, word := range ranks.Words {
		word.Weight = normalize(word.Weight, ranks.Min, ranks.Max)
	}

	for x, xMap := range ranks.Relation.Node {
		for y := range xMap {
			sentenceIDs := ranks.Relation.Node[x][y].SentenceIDs
			weight := algorithm.WeightingRelation(x, y, ranks)

			ranks.Relation.Node[x][y] = Score{
				ranks.Relation.Node[x][y].Qty,
				weight,
				sentenceIDs,
			}

			if ranks.Relation.Max < weight {
				ranks.Relation.Max = weight
			}

			if ranks.Relation.Min > weight || ranks.Relation.Min == 0 {
				ranks.Relation.Min = weight
			}
		}
	}

	for x, xMap := range ranks.Relation.Node {
		for y := range xMap {
			weight := normalize(
				ranks.Relation.Node[x][y].Weight,
				ranks.Relation.Min,
				ranks.Relation.Max,
			)

			ranks.Relation.Node[x][y] = Score{
				ranks.Relation.Node[x][y].Qty,
				weight,
				ranks.Relation.Node[x][y].SentenceIDs,
			}
		}
	}
}

func normalize(weight float32, min float32, max float32) float32 {
	return (weight - min) / (max - min)
}