Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aimacode
GitHub Repository: aimacode/aima-python
Path: blob/master/ipyviews.py
615 views
1
from IPython.display import HTML, display, clear_output
2
from collections import defaultdict
3
from agents import PolygonObstacle
4
import time
5
import json
6
import copy
7
import __main__
8
9
# ______________________________________________________________________________
10
# Continuous environment
11
12
13
_CONTINUOUS_WORLD_HTML = '''
14
<div>
15
<canvas class="main-robo-world" width="{0}" height="{1}" style="background:rgba(158, 167, 184, 0.2);" data-world_name="{2}" onclick="getPosition(this,event)"/>
16
</div>
17
18
<script type="text/javascript">
19
var all_polygons = {3};
20
{4}
21
</script>
22
''' # noqa
23
24
with open('js/continuousworld.js', 'r') as js_file:
25
_JS_CONTINUOUS_WORLD = js_file.read()
26
27
28
class ContinuousWorldView:
29
""" View for continuousworld Implementation in agents.py """
30
31
def __init__(self, world, fill="#AAA"):
32
self.time = time.time()
33
self.world = world
34
self.width = world.width
35
self.height = world.height
36
37
def object_name(self):
38
globals_in_main = {x: getattr(__main__, x) for x in dir(__main__)}
39
for x in globals_in_main:
40
if isinstance(globals_in_main[x], type(self)):
41
if globals_in_main[x].time == self.time:
42
return x
43
44
def handle_add_obstacle(self, vertices):
45
""" Vertices must be a nestedtuple. This method
46
is called from kernel.execute on completion of
47
a polygon. """
48
self.world.add_obstacle(vertices)
49
self.show()
50
51
def handle_remove_obstacle(self):
52
return NotImplementedError
53
54
def get_polygon_obstacles_coordinates(self):
55
obstacle_coordiantes = []
56
for thing in self.world.things:
57
if isinstance(thing, PolygonObstacle):
58
obstacle_coordiantes.append(thing.coordinates)
59
return obstacle_coordiantes
60
61
def show(self):
62
clear_output()
63
total_html = _CONTINUOUS_WORLD_HTML.format(self.width, self.height, self.object_name(),
64
str(self.get_polygon_obstacles_coordinates()),
65
_JS_CONTINUOUS_WORLD)
66
display(HTML(total_html))
67
68
69
# ______________________________________________________________________________
70
# Grid environment
71
72
_GRID_WORLD_HTML = '''
73
<div class="map-grid-world" >
74
<canvas data-world_name="{0}"></canvas>
75
<div style="min-height:20px;">
76
<span></span>
77
</div>
78
</div>
79
<script type="text/javascript">
80
var gridArray = {1} , size = {2} , elements = {3};
81
{4}
82
</script>
83
'''
84
85
with open('js/gridworld.js', 'r') as js_file:
86
_JS_GRID_WORLD = js_file.read()
87
88
89
class GridWorldView:
90
""" View for grid world. Uses XYEnviornment in agents.py as model.
91
world: an instance of XYEnviornment.
92
block_size: size of individual blocks in pixes.
93
default_fill: color of blocks. A hex value or name should be passed.
94
"""
95
96
def __init__(self, world, block_size=30, default_fill="white"):
97
self.time = time.time()
98
self.world = world
99
self.labels = defaultdict(str) # locations as keys
100
self.representation = {"default": {"type": "color", "source": default_fill}}
101
self.block_size = block_size
102
103
def object_name(self):
104
globals_in_main = {x: getattr(__main__, x) for x in dir(__main__)}
105
for x in globals_in_main:
106
if isinstance(globals_in_main[x], type(self)):
107
if globals_in_main[x].time == self.time:
108
return x
109
110
def set_label(self, coordinates, label):
111
""" Add lables to a particular block of grid.
112
coordinates: a tuple of (row, column).
113
rows and columns are 0 indexed.
114
"""
115
self.labels[coordinates] = label
116
117
def set_representation(self, thing, repr_type, source):
118
""" Set the representation of different things in the
119
environment.
120
thing: a thing object.
121
repr_type : type of representation can be either "color" or "img"
122
source: Hex value in case of color. Image path in case of image.
123
"""
124
thing_class_name = thing.__class__.__name__
125
if repr_type not in ("img", "color"):
126
raise ValueError('Invalid repr_type passed. Possible types are img/color')
127
self.representation[thing_class_name] = {"type": repr_type, "source": source}
128
129
def handle_click(self, coordinates):
130
""" This method needs to be overidden. Make sure to include a
131
self.show() call at the end. """
132
self.show()
133
134
def map_to_render(self):
135
default_representation = {"val": "default", "tooltip": ""}
136
world_map = [[copy.deepcopy(default_representation) for _ in range(self.world.width)]
137
for _ in range(self.world.height)]
138
139
for thing in self.world.things:
140
row, column = thing.location
141
thing_class_name = thing.__class__.__name__
142
if thing_class_name not in self.representation:
143
raise KeyError('Representation not found for {}'.format(thing_class_name))
144
world_map[row][column]["val"] = thing.__class__.__name__
145
146
for location, label in self.labels.items():
147
row, column = location
148
world_map[row][column]["tooltip"] = label
149
150
return json.dumps(world_map)
151
152
def show(self):
153
clear_output()
154
total_html = _GRID_WORLD_HTML.format(
155
self.object_name(), self.map_to_render(),
156
self.block_size, json.dumps(self.representation), _JS_GRID_WORLD)
157
display(HTML(total_html))
158
159