-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomsearch2.py
261 lines (195 loc) · 9.44 KB
/
randomsearch2.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
261
# UE IA & JEUX - L3, SU
# TP "comportement réactif"
#
# Nicolas Bredeche
# 2021-03-31
from pyroborobo import Pyroborobo, Controller, AgentObserver, WorldObserver, CircleObject, SquareObject, MovableObject
# from custom.controllers import SimpleController, HungryController
import numpy as np
import random
import math
import random
import paintwars_arena
rob = 0
# =-=-=-=-=-=-=-=-=-= NE RIEN MODIFIER *AVANT* CETTE LIGNE =-=-=-=-=-=-=-=-=-=
simulation_mode = 1 # Simulation mode: realtime=0, fast=1, super_fast_no_render=2 -- pendant la simulation, la touche "d" permet de passer d'un mode à l'autre.
posInit = (400,400)
param = []
bestParam = []
bestScore = 0
bestIteration = 0
score = 0
evaluations = 500
def step(robotId, sensors, position):
global evaluations, param, bestParam, bestScore, score, bestIteration
# cet exemple montre comment générer au hasard, et évaluer, des stratégies comportementales
# Remarques:
# - l'évaluation est ici la distance moyenne parcourue, mais on peut en imaginer d'autres
# - la liste "param", définie ci-dessus, permet de stocker les paramètres de la fonction de contrôle
# - la fonction de controle est une combinaison linéaire des senseurs, pondérés par les paramètres
# toutes les 400 itérations: le robot est remis au centre de l'arène avec une orientation aléatoire
if rob.iterations % 400 == 0 and evaluations > 0:
if rob.iterations > 0 :
score += math.sqrt( math.pow( posInit[0] - position[0], 2 ) + math.pow( posInit[1] - position[1], 2 ) )
evaluations -= 1
if (rob.iterations % 3 == 0) :
if score > bestScore :
bestScore = score
bestParam = param.copy()
bestIteration = rob.iterations
score = 0
param = []
for i in range(0, 8):
param.append(random.randint(-1, 1))
rob.controllers[robotId].set_position(posInit[0], posInit[1])
rob.controllers[robotId].set_absolute_orientation(random.uniform(0,360))
if evaluations == 0 :
param = bestParam.copy()
evaluations -= 1
if rob.iterations % 1000 == 0 and evaluations == -1 :
#print(f"BestScore = {bestScore}\nBestMoyenneDist = {bestScore / 3}\nBestParam = {bestParam}\nBestIteration = {bestIteration}\n\n")
rob.controllers[robotId].set_position(posInit[0], posInit[1])
rob.controllers[robotId].set_absolute_orientation(random.uniform(0,360))
# fonction de contrôle (qui dépend des entrées sensorielles, et des paramètres)
translation = math.tanh ( param[0] + param[1] * sensors["sensor_front_left"]["distance"] + param[2] * sensors["sensor_front"]["distance"] + param[3] * sensors["sensor_front_right"]["distance"] );
rotation = math.tanh ( param[4] + param[5] * sensors["sensor_front_left"]["distance"] + param[6] * sensors["sensor_front"]["distance"] + param[7] * sensors["sensor_front_right"]["distance"] );
return translation, rotation
# =-=-=-=-=-=-=-=-=-= NE RIEN MODIFIER *APRES* CETTE LIGNE =-=-=-=-=-=-=-=-=-=
number_of_robots = 1 # 8 robots identiques placés dans l'arène
arena = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
offset_x = 36
offset_y = 36
edge_width = 28
edge_height = 28
class MyController(Controller):
def __init__(self, wm):
super().__init__(wm)
def reset(self):
return
def step(self):
sensors = {}
sensors["sensor_left"] = {"distance": self.get_distance_at(0)}
sensors["sensor_front_left"] = {"distance": self.get_distance_at(1)}
sensors["sensor_front"] = {"distance": self.get_distance_at(2)}
sensors["sensor_front_right"] = {"distance": self.get_distance_at(3)}
sensors["sensor_right"] = {"distance": self.get_distance_at(4)}
sensors["sensor_back_right"] = {"distance": self.get_distance_at(5)}
sensors["sensor_back"] = {"distance": self.get_distance_at(6)}
sensors["sensor_back_left"] = {"distance": self.get_distance_at(7)}
translation, rotation = step(self.id, sensors, self.absolute_position)
self.set_translation(translation)
self.set_rotation(rotation)
def check(self):
# print (self.id)
return True
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class MyAgentObserver(AgentObserver):
def __init__(self, wm):
super().__init__(wm)
self.arena_size = Pyroborobo.get().arena_size
def reset(self):
super().reset()
return
def step_pre(self):
super().step_pre()
return
def step_post(self):
super().step_post()
return
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class MyWorldObserver(WorldObserver):
def __init__(self, world):
super().__init__(world)
rob = Pyroborobo.get()
def init_pre(self):
super().init_pre()
def init_post(self):
global offset_x, offset_y, edge_width, edge_height, rob
super().init_post()
for i in range(len(arena)):
for j in range(len(arena[0])):
if arena[i][j] == 1:
block = BlockObject()
block = rob.add_object(block)
block.soft_width = 0
block.soft_height = 0
block.solid_width = edge_width
block.solid_height = edge_height
block.set_color(164, 128, 0)
block.set_coordinates(offset_x + j * edge_width, offset_y + i * edge_height)
retValue = block.can_register()
# print("Register block (",block.get_id(),") :", retValue)
block.register()
block.show()
counter = 0
for robot in rob.controllers:
x = 260 + counter*40
y = 400
robot.set_position(x, y)
counter += 1
def step_pre(self):
super().step_pre()
def step_post(self):
super().step_post()
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class Tile(SquareObject): # CircleObject):
def __init__(self, id=-1, data={}):
super().__init__(id, data)
self.owner = "nobody"
def step(self):
return
def is_walked(self, id_):
return
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class BlockObject(SquareObject):
def __init__(self, id=-1, data={}):
super().__init__(id, data)
def step(self):
return
def is_walked(self, id_):
return
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def main():
global rob
rob = Pyroborobo.create(
"config/paintwars.properties",
controller_class=MyController,
world_observer_class=MyWorldObserver,
# world_model_class=PyWorldModel,
agent_observer_class=MyAgentObserver,
object_class_dict={}
,override_conf_dict={"gInitialNumberOfRobots": number_of_robots, "gDisplayMode": simulation_mode}
)
rob.start()
rob.update(1000000)
rob.close()
if __name__ == "__main__":
main()