-
Notifications
You must be signed in to change notification settings - Fork 0
/
spatial_learning.py
260 lines (213 loc) · 8.93 KB
/
spatial_learning.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""
spatial_learning.py
"""
class Room(object):
"""A Room has position (x, y) knows its relations to other Room objects
Note that the origin is defined as the lower left corner as in Cartesian coordinates"""
all_rooms = {}
def __new__(cls, x, y):
"""Constructs a Room with the given position (x, y)"""
if (x, y) not in cls.all_rooms:
obj = super(Room, cls).__new__(cls)
obj.x = x
obj.y = y
cls.all_rooms[(x, y)] = obj
return cls.all_rooms[(x, y)]
def is_not_on(self, other):
"""Returns true if self is in the same position (x, y) as other, false otherwise"""
return not (self.x == other.x and self.y == other.y)
def is_in_back_of(self, other):
"""Returns true if self is in the back of other, false otherwise
An object is considered in back of if its y-coordinate is greater"""
return self.y > other.y
def is_in_front_of(self, other):
"""Returns true if self in in front of other, false otherwise"""
return other.is_in_back_of(self)
def is_left_of(self, other):
"""Returns true if self is left of other, false otherwise"""
return self.x < other.x
def is_right_of(self, other):
"""Returns true if self is right of other, false otherwise"""
return other.is_left_of(self)
def copy(self):
new_room = Room(self.x, self.y)
return new_room
def __str__(self):
"""Returns the string representation of this Room"""
return "(%d, %d)" % (self.x, self.y)
class World(object):
"""A World has animals and sets them to Rooms given constraints"""
def __init__(self, animals=None):
"""Constructs a World with the given animals with Rooms initialized to None"""
if type(animals) is dict:
self.animals = animals
else:
self.animals = {}
if animals is None:
animals = []
for a in animals:
self.animals[a] = None
def set_position(self, animal, x, y):
"""Sets the given animal to a new Room at position (x, y) and returns the room.
Adds the animal to animals if it does not already exist.
Raises a ValueError if the animal is already set."""
if animal not in self.animals:
self.animals[animal] = None
if self.animals[animal] is None:
room = Room(x, y)
self.animals[animal] = room
return room
else:
raise ValueError("Animal %s is already set at (%d, %d)" % (animal, self.animals[animal].x, self.animals[animal].y))
def test_constraint(self, constraint):
"""Tests whether the given constraint is satisfied"""
animal1, relation, animal2 = constraint
if self.animals[animal1] is None:
return True
if self.animals[animal2] is None:
return True
if relation == 'is not on':
return self.animals[animal1].is_not_on(self.animals[animal2])
elif relation == "in front of":
return self.animals[animal1].is_in_front_of(self.animals[animal2])
elif relation == "in back of":
return self.animals[animal1].is_in_back_of(self.animals[animal2])
elif relation == "left of":
return self.animals[animal1].is_left_of(self.animals[animal2])
else:
return self.animals[animal1].is_right_of(self.animals[animal2])
def copy(self):
"""Creates and returns a copy of this World"""
new_animals = {}
for a in self.animals:
if self.animals[a] is None:
new_animals[a] = None
else:
new_animals[a] = self.animals[a].copy()
new_world = World(new_animals)
return new_world
def __str__(self):
"""Returns the string representation of this World"""
output = []
for animal in self.animals:
output.append("%s:%s" % (animal, self.animals[animal]))
return "<" + ", ".join(output) + ">"
class Experiment(object):
def __init__(self, animals=None, constraints=None):
"""Initializes an experiment with all possible worlds given animals and constraints"""
self.valid_relations = ['left of', 'right of', 'in front of', 'in back of']
if animals is None:
animals = []
if constraints is None:
constraints = []
for a in animals:
for b in animals:
if b != a:
constraint = (a, 'is not on', b)
constraints.append(constraint)
self.animals = animals
self.constraints = constraints
self.possible_worlds = []
self.update()
def update(self):
"""Updates the possible worlds for this Experiment"""
num_animals = len(self.animals)
#Initialize the first animal (constraints trivial) to all positions
self.possible_worlds = []
for x in xrange(num_animals):
for y in xrange(num_animals):
world = World(self.animals)
world.set_position(self.animals[0], x, y)
self.possible_worlds.append(world)
for animal in self.animals[1:]:
new_possible_worlds = []
for world in self.possible_worlds:
new_worlds = []
if animal not in world.animals.keys():
world.animals[animal] = None
for x in xrange(num_animals):
for y in xrange(num_animals):
new_world = world.copy()
new_world.set_position(animal, x, y)
valid = True
for constraint in self.constraints:
valid = new_world.test_constraint(constraint)
if not valid:
break
if valid:
new_worlds.append(new_world)
if len(new_worlds) > 0:
for w in new_worlds:
new_possible_worlds.append(w)
self.possible_worlds = new_possible_worlds
# print "-"*70
# print 'Possible worlds:'
# for i in self.possible_worlds:
# print i
def add_animal(self, animal):
"""Adds the animal to the list of animals in this Experiment.
Does nothing if the animal already exists."""
if animal not in self.animals:
self.animals.append(animal)
#self.update()
def add_constraint(self, constraint):
"""Adds the constraint to the list of constraints in this Experiment.
Adds animals included in the constraint as needed."""
if type(constraint) is not tuple or len(constraint) < 3:
raise ValueError("Invalid constraint format")
elif constraint[1] not in self.valid_relations:
raise ValueError("Invalid relation %s" % constraint[1])
self.add_animal(constraint[0])
self.add_animal(constraint[2])
self.constraints.append(constraint)
#self.update()
def main(*args):
animals = []
constraints = []
while True:
animal = raw_input("Enter animal (return to end): ")
if animal == "":
break
animals.append(animal)
experiment = Experiment(None, constraints)
for a in animals:
experiment.add_animal(a)
print("\nConstraint format: animal1, relation, animal2")
print("Valid relations are %s" % experiment.valid_relations)
while True:
try:
constraint = raw_input("Enter constraint (return to end): ")
if constraint == "":
break
constraint_tuple = tuple(x.strip() for x in constraint.split(','))
experiment.add_constraint(constraint_tuple)
except ValueError as e:
print(e)
pass
experiment.update()
#End result print statements
# print("animals: %s" % experiment.animals)
# print("constraints: %s" % experiment.constraints)
# print("worlds:\n%s" % experiment.possible_worlds)
print(len(experiment.possible_worlds))
for w in experiment.possible_worlds:
print(w)
if __name__ == "__main__":
Experiment().main()
# animals = ['cat', 'dog', 'bear', 'rabbit', 'pig', 'frog']
# constraints = [
# ('cat', 'left of', 'rabbit'),
# ('pig', 'left of', 'cat'),
# ('dog', 'in front of', 'pig'),
# ('bear', 'right of', 'dog'),
# ('frog', 'right of', 'bear')
# ]
# experiment = Experiment()
# for a in animals:
# experiment.add_animal(a)
# for c in constraints:
# experiment.add_constraint(c)
# experiment.update()
# for w in experiment.possible_worlds:
# print w
# print len(experiment.possible_worlds)