-
Notifications
You must be signed in to change notification settings - Fork 0
/
constraintnetwork.py
101 lines (83 loc) · 2.85 KB
/
constraintnetwork.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
import variable
import constraint
# import assignment
class ConstraintNetwork:
def __init__(self):
"""
CSP representation of the problem. Contains the variables, constraints, and
many helpful accessors.
"""
self.constraints = []
self.variables = []
######### Modifiers Method #########
def addConstraint(self, c):
if c not in self.constraints:
self.constraints.append(c)
def addVariable(self, v):
if v not in self.variables:
self.variables.append(v)
# def pushAssignment(self, a):
# """
# Used for Local Search. Assigns a value to a variable based on the parameter a
# @param a Assignment to actualize
# """
# a.variable.assignValue(a.value)
######### Accessors Method #########
def getNeighborsOfVariable(self, v):
neighbors = set()
for c in self.constraints:
if c.contains(v):
for x in c.vars:
neighbors.add(x)
neighbors.remove(v)
return list(neighbors)
# def isConsistent(self):
# """
# Used for local search. Determines if the current assignment is consistent.
# """
# for c in self.constraints:
# return c.isConsistent()
# return True
def getConstraintsContainingVariable(self, v):
"""
@param v variable to check
@return list of constraints that contains v
"""
outList = []
for c in self.constraints:
if c.contains(v):
outList.append(c)
return outList
def getModifiedConstraints(self):
"""
Returns the constraints that contain variables whose domains were
modified since the last call to this method.
After getting the constraints, it will reset each variable to
unmodified
Note* The first call to this method returns the constraints containing
the initialized variables.
@return ArrayList of modified constraints
"""
mConstraints = []
for c in self.constraints:
if c.isModified():
mConstraints.append(c)
for v in self.variables:
v.setModified(False)
return mConstraints
######### String Representation #########
def __str__(self):
output = str(len(self.variables)) + " Variables: {"
delim = ""
for v in self.variables:
output += delim + v.name
delim = ","
output += "}"
output += "\n" + str(len(self.constraints)) + " Constraints:"
delim = "\n"
for c in self.constraints:
output += delim + str(c)
output += "\n"
for v in self.variables:
output += str(v) + "\n"
return output