-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVertexColoringProblem.py
124 lines (89 loc) · 2.5 KB
/
VertexColoringProblem.py
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
from Graph import *
from BP import BP
from math import e
class EdgePotential(Potential):
def __init__(self):
Potential.__init__(self)
def get(self, parameters):
return 1 if parameters[0] != parameters[1] else 0
class NodePotential(Potential):
def __init__(self, weights):
Potential.__init__(self)
self.weights = weights
def get(self, parameters):
return e ** self.weights[parameters[0]]
def print_prob(A, w, its, max_prod=True):
n = len(A)
domain = Domain(tuple(range(len(w))))
edge_potential = EdgePotential()
node_potential = NodePotential(w)
rvs = list()
factors = list()
for i in range(n):
rv = RV(domain, value=None)
rvs.append(rv)
factors.append(
F(node_potential, (rv,))
)
for i in range(n):
for j in range(n):
if i < j and A[i, j] == 1:
factors.append(
F(edge_potential, (rvs[i], rvs[j]))
)
g = Graph(rvs, factors)
bp = BP(g, max_prod=max_prod)
bp.run(iteration=its)
p = list()
for i in range(n):
p.append(bp.prob(rvs[i]))
return p
def sumprod(A, w, its):
n = len(A)
domain = Domain(tuple(range(len(w))))
edge_potential = EdgePotential()
node_potential = NodePotential(w)
rvs = list()
factors = list()
for i in range(n):
rv = RV(domain, value=None)
rvs.append(rv)
factors.append(
F(node_potential, (rv,))
)
for i in range(n):
for j in range(n):
if i < j and A[i, j] == 1:
factors.append(
F(edge_potential, (rvs[i], rvs[j]))
)
g = Graph(rvs, factors)
bp = BP(g)
bp.run(iteration=its)
return bp.partition()
def maxprod(A, w, its):
n = len(A)
domain = Domain(tuple(range(len(w))))
edge_potential = EdgePotential()
node_potential = NodePotential(w)
rvs = list()
factors = list()
for i in range(n):
rv = RV(domain, value=None)
rvs.append(rv)
factors.append(
F(node_potential, (rv,))
)
for i in range(n):
for j in range(n):
if i < j and A[i, j] == 1:
factors.append(
F(edge_potential, (rvs[i], rvs[j]))
)
g = Graph(rvs, factors)
bp = BP(g, max_prod=True)
bp.run(iteration=its)
x = list()
for i in range(n):
x.append(bp.map(rvs[i]))
return x