Example #1
0
def run_sim(nodes):
    print(nodes)
    brewer = BeamNGBrewer(road_nodes=nodes)
    beamng = brewer.beamng
    waypoint_goal = BeamNGWaypoint('waypoint_goal', get_node_coords(nodes[-1]))
    maps.install_map_if_needed()
    maps.beamng_map.generated().write_items(brewer.decal_road.to_json() +
                                            '\n' + waypoint_goal.to_json())
    vehicle = brewer.setup_vehicle()
    brewer.vehicle_start_pose = brewer.road_points.vehicle_start_pose()
    #camera = brewer.setup_scenario_camera()
    street_1 = brewer.decal_road
    sim_data_collector = TrainingDataCollectorAndWriter(
        vehicle, beamng, street_1)
    brewer.bring_up()

    steps = 5

    def start():
        for idx in range(1000):
            if (idx * 0.05 * steps) > 3.:
                sim_data_collector.collect_and_write_current_data()
                dist = points_distance(sim_data_collector.last_state.pos,
                                       waypoint_goal.position)
                if dist < 15.0:
                    beamng.resume()
                    break

            # one step is 0.05 seconds (5/100)
            beamng.step(steps)

    try:
        start()
    finally:

        beamng.close()
    def _run_simulation(self, nodes) -> SimulationData:
        if not self.brewer:
            self.brewer = BeamNGBrewer()
            self.vehicle = self.brewer.setup_vehicle()
            self.camera = self.brewer.setup_scenario_camera()

        brewer = self.brewer
        brewer.setup_road_nodes(nodes)
        beamng = brewer.beamng
        waypoint_goal = BeamNGWaypoint('waypoint_goal', get_node_coords(nodes[-1]))
        maps.install_map_if_needed()
        maps.beamng_map.generated().write_items(brewer.decal_road.to_json() + '\n' + waypoint_goal.to_json())

        cameras = BeamNGCarCameras()
        vehicle_state_reader = VehicleStateReader(self.vehicle, beamng, additional_sensors=cameras.cameras_array)
        brewer.vehicle_start_pose = brewer.road_points.vehicle_start_pose()

        steps = brewer.params.beamng_steps
        simulation_id = time.strftime('%Y-%m-%d--%H-%M-%S', time.localtime())
        name = self.config.simulation_name.replace('$(id)', simulation_id)
        sim_data_collector = SimulationDataCollector(self.vehicle, beamng, brewer.decal_road, brewer.params,
                                                     vehicle_state_reader=vehicle_state_reader,
                                                     camera=self.camera,
                                                     simulation_name=name)

        sim_data_collector.get_simulation_data().start()
        try:
            brewer.bring_up()
            from keras.models import load_model
            if not self.model:
                self.model = load_model(self.model_file)
            predict = NvidiaPrediction(self.model, self.config)
            iterations_count = 1000
            idx = 0
            while True:
                idx += 1
                if idx >= iterations_count:
                    sim_data_collector.save()
                    raise Exception('Timeout simulation ', sim_data_collector.name)

                sim_data_collector.collect_current_data(oob_bb=False)
                last_state: SimulationDataRecord = sim_data_collector.states[-1]
                if points_distance(last_state.pos, waypoint_goal.position) < 15.0:
                    break

                if last_state.is_oob:
                    break
                img = vehicle_state_reader.sensors['cam_center']['colour'].convert('RGB')
                steering_angle, throttle = predict.predict(img, last_state)
                self.vehicle.control(throttle=throttle, steering=steering_angle, brake=0)
                beamng.step(steps)

            sim_data_collector.get_simulation_data().end(success=True)
        except Exception as ex:
            sim_data_collector.get_simulation_data().end(success=False, exception=ex)
            traceback.print_exception(type(ex), ex, ex.__traceback__)
        finally:
            if self.config.simulation_save:
                sim_data_collector.save()
                try:
                    sim_data_collector.take_car_picture_if_needed()
                except:
                    pass

            self.end_iteration()

        return sim_data_collector.simulation_data
Example #3
0
    def _run_simulation(self, the_test) -> SimulationData:
        if not self.brewer:
            self.brewer = BeamNGBrewer(beamng_home=self.beamng_home,
                                       beamng_user=self.beamng_user)
            self.vehicle = self.brewer.setup_vehicle()

        # For the execution we need the interpolated points
        nodes = the_test.interpolated_points

        brewer = self.brewer
        brewer.setup_road_nodes(nodes)
        beamng = brewer.beamng
        waypoint_goal = BeamNGWaypoint('waypoint_goal',
                                       get_node_coords(nodes[-1]))

        # TODO Make sure that maps points to the right folder !
        if self.beamng_user is not None:
            beamng_levels = LevelsFolder(
                os.path.join(self.beamng_user, 'levels'))
            maps.beamng_levels = beamng_levels
            maps.beamng_map = maps.beamng_levels.get_map('tig')
            # maps.print_paths()

        maps.install_map_if_needed()
        maps.beamng_map.generated().write_items(brewer.decal_road.to_json() +
                                                '\n' + waypoint_goal.to_json())

        vehicle_state_reader = VehicleStateReader(self.vehicle,
                                                  beamng,
                                                  additional_sensors=None)
        brewer.vehicle_start_pose = brewer.road_points.vehicle_start_pose()

        steps = brewer.params.beamng_steps
        simulation_id = time.strftime('%Y-%m-%d--%H-%M-%S', time.localtime())
        name = 'beamng_executor/sim_$(id)'.replace('$(id)', simulation_id)
        sim_data_collector = SimulationDataCollector(
            self.vehicle,
            beamng,
            brewer.decal_road,
            brewer.params,
            vehicle_state_reader=vehicle_state_reader,
            simulation_name=name)

        # TODO: Hacky - Not sure what's the best way to set this...
        sim_data_collector.oob_monitor.tolerance = self.oob_tolerance

        sim_data_collector.get_simulation_data().start()
        try:
            #start = timeit.default_timer()
            brewer.bring_up()
            # iterations_count = int(self.test_time_budget/250)
            # idx = 0

            brewer.vehicle.ai_set_aggression(self.risk_value)
            # TODO This does not seem to take any effect...
            brewer.vehicle.ai_set_speed(self.maxspeed, mode='limit')
            brewer.vehicle.ai_drive_in_lane(True)
            brewer.vehicle.ai_set_waypoint(waypoint_goal.name)

            while True:
                # idx += 1
                # assert idx < iterations_count, "Timeout Simulation " + str(sim_data_collector.name)

                sim_data_collector.collect_current_data(oob_bb=True)
                last_state: SimulationDataRecord = sim_data_collector.states[
                    -1]
                # Target point reached
                if points_distance(last_state.pos,
                                   waypoint_goal.position) < 8.0:
                    break

                assert self._is_the_car_moving(
                    last_state), "Car is not moving fast enough " + str(
                        sim_data_collector.name)

                assert not last_state.is_oob, "Car drove out of the lane " + str(
                    sim_data_collector.name)

                beamng.step(steps)

            sim_data_collector.get_simulation_data().end(success=True)
            #end = timeit.default_timer()
            #run_elapsed_time = end-start
            #run_elapsed_time = float(last_state.timer)
            self.total_elapsed_time = self.get_elapsed_time()
        except AssertionError as aex:
            sim_data_collector.save()
            # An assertion that trigger is still a successful test execution, otherwise it will count as ERROR
            sim_data_collector.get_simulation_data().end(success=True,
                                                         exception=aex)
            traceback.print_exception(type(aex), aex, aex.__traceback__)
        except Exception as ex:
            sim_data_collector.save()
            sim_data_collector.get_simulation_data().end(success=False,
                                                         exception=ex)
            traceback.print_exception(type(ex), ex, ex.__traceback__)
        finally:
            sim_data_collector.save()
            try:
                sim_data_collector.take_car_picture_if_needed()
            except:
                pass

            self.end_iteration()

        return sim_data_collector.simulation_data
import random
from time import sleep
from typing import Tuple, List

import numpy as np

from self_driving.beamng_brewer import BeamNGBrewer
from udacity_integration.beamng_car_cameras import BeamNGCarCameras
from self_driving.road_generator import RoadGenerator
from self_driving.beamng_tig_maps import maps
from self_driving.beamng_waypoint import BeamNGWaypoint
from self_driving.decal_road import DecalRoad
from udacity_integration.training_data_collector_and_writer import TrainingDataCollectorAndWriter
from self_driving.utils import get_node_coords

maps.install_map_if_needed()
STEPS = 5

# x is -y and *angle direction is reversed*
def get_rotation(road: DecalRoad):
    v1 = road.nodes[0][:2]
    v2 = road.nodes[1][:2]
    v = np.subtract(v1, v2)
    deg = np.degrees(np.arctan2([v[0]], [v[1]]))
    return (0, 0, deg)


def get_script_point(p1, p2) -> Tuple[Tuple, Tuple]:
    a = np.subtract(p2[0:2], p1[0:2])

    # calculate the vector which length is half the road width