1package rank
 2
 3// Relation struct contains the phrase data.
 4//
 5// Max is the occurrence of the most used phrase.
 6//
 7// Min is the occurrence of the less used phrase. It is always greater then 0.
 8//
 9// Node is contains the Scores. Firs ID is the word 1, second ID is the word 2,
10// and the value is the Score what contains the data about their relation.
11type Relation struct {
12	Max  float32
13	Min  float32
14	Node map[int]map[int]Score
15}
16
17// Score struct contains data about a relation of two words.
18//
19// Qty is the occurrence of the phrase.
20//
21// Weight is the weight of the phrase between 0.00 and 1.00.
22//
23// SentenceIDs contains all IDs of sentences what contain the phrase.
24type Score struct {
25	Qty         int
26	Weight      float32
27	SentenceIDs []int
28}
29
30// AddRelation method adds a new relation to Relation object.
31func (relation *Relation) AddRelation(wordID int, relatedWordID int, sentenceID int) {
32	if relatedWordID == -1 {
33		return
34	}
35
36	if relation.updateRelation(relatedWordID, wordID, true, sentenceID) {
37		return
38	}
39
40	if relation.extendRelation(wordID, relatedWordID, true, sentenceID) {
41		return
42	}
43
44	relation.createRelation(wordID, relatedWordID, sentenceID)
45}
46
47func (relation *Relation) updateRelation(x int, y int, r bool, sentenceID int) bool {
48	if _, ok := relation.Node[x][y]; ok {
49		count := relation.Node[x][y].Qty + 1
50		weight := relation.Node[x][y].Weight
51		sentenceIDs := append(relation.Node[x][y].SentenceIDs, sentenceID)
52		relation.Node[x][y] = Score{count, weight, sentenceIDs}
53
54		return true
55	} else if r {
56		return relation.updateRelation(y, x, false, sentenceID)
57	}
58
59	return false
60}
61
62func (relation *Relation) extendRelation(x int, y int, r bool, sentenceID int) bool {
63	if _, ok := relation.Node[x]; ok {
64		relation.Node[x][y] = Score{1, 0, []int{sentenceID}}
65
66		return true
67	} else if r {
68		return relation.extendRelation(y, x, false, sentenceID)
69	}
70
71	return false
72}
73
74func (relation *Relation) createRelation(x int, y int, sentenceID int) {
75	relation.Node[x] = map[int]Score{}
76	relation.Node[x][y] = Score{1, 0, []int{sentenceID}}
77}