Skip to content

Commit 11021ea

Browse files
updated docker cp to host
1 parent 24bc769 commit 11021ea

6 files changed

Lines changed: 108 additions & 30 deletions

File tree

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
from basic_algorithm import BasicAlgorithm
22
import lanelet2
33
import random
4+
import json
45

56
from math import sqrt, pow
67

78

8-
class Hill_Climb(BasicAlgorithm):
9+
class HillClimb(BasicAlgorithm):
910
def __init__(self, args: dict) -> None:
1011
super(BasicAlgorithm).__init__()
1112
self.radius = args["radius"]
@@ -20,7 +21,7 @@ def _scenario_callback(
2021
self, scenario_definition: dict, driving_score: float
2122
) -> dict:
2223
# pass in route id
23-
waypoints = scenario_definition["routes"][0]["waypoints"]
24+
waypoints = scenario_definition["routes"][0]["route"]["waypoints"]
2425

2526
if self.prev_ds is not None:
2627
if not driving_score >= self.prev_ds:
@@ -78,9 +79,24 @@ def __get_all_lanelet_points(self) -> set[tuple[int, int]]:
7879
centerline_points = []
7980
for lanelet in list(lanelets):
8081
for points in lanelet.centerline:
81-
centerline_points += (points.x, points.y)
82+
centerline_points.append((points.x, points.y))
8283

8384
return set(centerline_points)
8485

8586
def __euclidian_distance(self, point1, point2) -> float:
86-
return sqrt(pow(point1.x - point2.x, 2) + pow(point2.y - point1.x, 2))
87+
return sqrt(pow(point1[0] - point2[0], 2) + pow(point2[1] - point1[1], 2))
88+
89+
90+
def main(): # debug
91+
scenario = "/autoware_scenario_runner/example_scenario_default.json"
92+
93+
json_scenario = None
94+
with open(scenario, "r") as f:
95+
json_scenario = json.load(f)
96+
97+
radius = 10
98+
lanelet2_path = "/autoware_scenario_runner/algorithms/resources/Town01.osm"
99+
args = {"radius": radius, "lanelet_path": lanelet2_path}
100+
101+
climb = HillClimb(args)
102+
climb._scenario_callback(json_scenario, 0.0)

aw_scenario_runner.py

Lines changed: 56 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,15 @@
3434

3535
logger = logging.getLogger("scenario-runner")
3636

37+
infractions_dict = {
38+
"OutsideRouteLanesTest": 0.3,
39+
"CollisionTest": 1.0,
40+
"RunningRedLightTest": 0.4,
41+
"RunningStopTest": 0.25,
42+
}
43+
44+
terminations_dict = {"AgentBlockedTest": 0.0}
45+
3746

3847
class AWScenarioRunner(object):
3948
# flags
@@ -50,6 +59,7 @@ class AWScenarioRunner(object):
5059
definition_manager = None
5160

5261
aw_agent = None
62+
host_volume = os.environ["SR_HOST_VOLUME"]
5363

5464
def __init__(self, config: dict) -> None:
5565
"""
@@ -178,12 +188,14 @@ def run_scenario(
178188
# allow the agent to localise and set the route
179189
budget = int(self._scenario_config["initialisation_budget"])
180190
status = False # completion status
181-
for tick in range(0, budget):
191+
for tick in range(1, budget + 1):
182192
self.carla_world.tick()
183193
status = route_config.agent.run_step_init() # type: ignore
184194

185-
if status:
186-
logger.info(f"Successfully initialised agent in {tick} ticks")
195+
if not status:
196+
logger.info("Agent failed to initialise route.")
197+
else:
198+
logger.info("Successfully initialised agent; route set.")
187199

188200
if self._tm_config["active"]:
189201
logger.info("Loading Traffic Manager...")
@@ -194,7 +206,7 @@ def run_scenario(
194206
tm.set_random_device_seed(int(self._tm_config["seed"])) # ADD TO CONFIG
195207
tm.set_synchronous_mode(self._tm_config["sync"])
196208

197-
try: # the route gets sent to the agent here
209+
try:
198210
scenario = RouteScenario(
199211
world=self.carla_world,
200212
config=route_config,
@@ -208,14 +220,12 @@ def run_scenario(
208220

209221
logger.info("Starting scenario...")
210222
try:
211-
# recorder_name = f"{self.results_manager.last_scenario}/recording.log"
212-
# self.carla_client.start_recorder(recorder_name, True)
223+
self.carla_client.start_recorder("/home/carla/recording.log", True)
213224
self.scenario_manager.load_scenario(
214225
scenario, self.aw_agent, follow_ego=self._scenario_config["follow_ego"]
215226
)
216227
self.scenario_manager.run_scenario()
217-
218-
# self.carla_client.stop_recorder()
228+
self.carla_client.stop_recorder()
219229
result = True
220230
except Exception:
221231
traceback.print_exc()
@@ -269,7 +279,7 @@ def run(self) -> None:
269279
for iteration in range(self.iterations):
270280
logger.info("Starting CARLA container....")
271281
CARLAManager.restart_carla()
272-
time.sleep(5)
282+
time.sleep(5) # allow CARLA to load
273283

274284
self.curr_iteration = iteration
275285
logger.info(f"Starting algorithm iteration number {self.curr_iteration}")
@@ -297,7 +307,7 @@ def run(self) -> None:
297307
scenario_result.put(result_dict)
298308

299309
scenario_process = multiprocessing.Process(
300-
target=self.run_scenario,
310+
target=self.run_scenario, # need to catch connection exception
301311
args=(
302312
route_config,
303313
env_config,
@@ -316,7 +326,18 @@ def run(self) -> None:
316326
if scenario_process.is_alive():
317327
scenario_process.kill()
318328

329+
# copy over the recording from CARLA container if env variable is setup
330+
if self.host_volume is not None:
331+
CARLAManager.fetch_file(
332+
"/home/carla/recording.log",
333+
f"{self.host_volume}/{self.results_manager.last_scenario}/recording.log",
334+
)
335+
336+
logger.info("Calculating driving score...")
319337
driving_score = self._calculate_driving_score(result["criteria"])
338+
logger.info(
339+
f"Scenario iteration {iteration} achieved a score of {driving_score}"
340+
)
320341

321342
# read the scenario definition
322343
if not self.DEV_MODE:
@@ -352,8 +373,31 @@ def _output_criteria(
352373
return criteria_dict
353374

354375
def _calculate_driving_score(self, criteria: dict) -> float:
355-
# to be implemented
356-
return 0.0
376+
driving_score = 0.0
377+
378+
for key in terminations_dict.keys():
379+
if not criteria[key]["success_value"] == criteria[key]["actual_value"]:
380+
logger.info(f"Found terminal condition {key}.")
381+
return 0.0 # hit a termination condition, driving score of 0.0
382+
383+
completed_route = float(criteria["RouteCompletionTest"]["actual_value"]) / 100
384+
logger.info(f"Agent route completion: {completed_route * 100}%")
385+
386+
logger.info("Checking penality conditions...")
387+
penalties = 1
388+
for infraction, penalty in infractions_dict.items():
389+
delta_penalty = float(criteria[infraction]["actual_value"] * penalty)
390+
391+
if delta_penalty:
392+
logger.info(
393+
f"Condition {infraction}: Breached {criteria[infraction]['actual_value']} times"
394+
)
395+
logger.info(f"Applying penalty of {delta_penalty}")
396+
else:
397+
logger.info(f"Condition {infraction}: Found zero breaches")
398+
399+
driving_score = completed_route * (1 / penalties)
400+
return driving_score
357401

358402
def destroy(self) -> None:
359403
"""Deletes instances of all classes related to CARLA"""

config.yaml

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
log:
22
path: 'logs/'
33
clear_old_logs: true
4-
log_format: '[%(levelname)s] [%(asctime)s] [%(message)s] [%(filename)s]:[%(lineno)d]'
4+
log_format: '[%(levelname)s] [%(created)f] [%(filename)s] %(message)s'
55
carla:
66
host: 127.0.0.1
77
fidelity: 'Low'
@@ -10,20 +10,21 @@ carla:
1010
sync: true
1111
fixed_delta_seconds: 0.05 # update rate 1 / FPS
1212
traffic_manager:
13-
active: false
13+
active: true
1414
sync: true # must be the same as carla sync
1515
seed: 0
1616
port: 8001
1717
scenario_runner:
1818
debug: false
1919
dev_mode: false
20-
follow_ego: false # camera to follow ego vehicle
20+
follow_ego: true
2121
json: ./example_scenario.json
2222
route_id: 0
2323
agent: srunner/autoagents/autoware_agent
2424
initialisation_budget: 200 # ticks
2525
algorithm:
2626
iterations: 10
27-
path: algorithms/test_alg # relative path
27+
path: algorithms/test_alg
2828
args: # will be passed into the algorithm class as a dict
29-
test_arg: 10
29+
lanelet_path: /autoware_scenario_runner/algorithms/resources/Town01.osm
30+
radius: 10

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ six
1313
simple-watchdog-timer
1414
antlr4-python3-runtime==4.10
1515
graphviz
16+
lanelet2

srunner/scenarios/route_scenario.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
)
4747

4848
from srunner.scenarios.basic_scenario import BasicScenario
49+
from srunner.scenarios.background_activity import BackgroundBehavior
4950
from srunner.scenariomanager.weather_sim import RouteWeatherBehavior
5051
from srunner.scenariomanager.lights_sim import RouteLightsBehavior
5152
from srunner.scenariomanager.timer import RouteTimeoutBehavior
@@ -63,10 +64,6 @@ class RouteScenario(BasicScenario):
6364
along which several smaller scenarios are triggered
6465
"""
6566

66-
# fix route scenario
67-
# take in a pre-spawned ego vehicle
68-
# position it at the first waypoint in the route
69-
7067
def __init__(
7168
self,
7269
world,
@@ -373,11 +370,11 @@ def _create_behavior(self):
373370
) # Tick the ScenarioTriggerer before the scenarios
374371

375372
# Add the Background Activity
376-
# behavior.add_child(
377-
# BackgroundBehavior(
378-
# self.ego_vehicles[0], self.route, name="BackgroundActivity"
379-
# )
380-
# )
373+
behavior.add_child(
374+
BackgroundBehavior(
375+
self.ego_vehicles[0], self.route, name="BackgroundActivity"
376+
)
377+
)
381378

382379
behavior.add_children(scenario_behaviors)
383380
return behavior

srunner/tools/CARLA_manager.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,25 @@ def stop_carla():
5757
logger.info(f"Kill stdout: {result.stdout.strip()}")
5858
CARLAManager.container_id = None
5959

60+
@staticmethod
61+
def fetch_file(path: str, dest: str):
62+
if CARLAManager.container_id is not None:
63+
env = os.environ.copy()
64+
result = subprocess.run(
65+
f"docker cp {CARLAManager.container_id}:{path} {dest}",
66+
shell=True,
67+
text=True,
68+
capture_output=True,
69+
env=env,
70+
)
71+
logger.info(
72+
f"Copying... {path} from container {CARLAManager.container_id} to {dest}"
73+
)
74+
logger.info(f"docker cp {CARLAManager.container_id}:{path} {dest}")
75+
76+
if not result.returncode == 0:
77+
logger.info(f"Failed to copy {path} to {dest}")
78+
6079
@staticmethod
6180
def restart_carla():
6281
if CARLAManager.container_id is not None:

0 commit comments

Comments
 (0)