Пример #1
0
    def _build_background(self, background_definition, timeout):
        """
        Build background scenario. Adding pedestrians and vehicles wandering
        around.
        :param background_definition:
        :param timeout:
        :return:
        """

        scenario_configuration = ScenarioConfiguration()
        scenario_configuration.route = None
        scenario_configuration.town = self._town_name
        # TODO The random seed should be set.
        # Also the crossing factor should be specified on the benchmark itself.
        configuration_instances_vehicles = []
        configuration_instances_walkers = []
        # If there are walkers there should be cross factors otherwise it is 0
        cross_factor = 0.0

        if 'walker.*'  in background_definition:

            model = 'walker'
            transform = carla.Transform()
            autopilot = True
            random_location = True
            actor_configuration_instance = ActorConfigurationData(model, transform,
                                                                  autopilot=autopilot,
                                                                  random=random_location,
                                                                  amount=int(
                                                                      background_definition[
                                                                          'walker.*']),
                                                                  category='walker')
            configuration_instances_walkers.append(actor_configuration_instance)

            if "cross_factor" not in background_definition:
                raise ValueError(" If there are walkers on the json file "
                                 "background scenario there must also be a cross factor")

            cross_factor = background_definition["cross_factor"]

        if 'vehicle.*' in background_definition:
            model = 'vehicle'
            transform = carla.Transform()
            autopilot = True
            random_location = True
            actor_configuration_instance = ActorConfigurationData(model, transform,
                                                                  autopilot=autopilot,
                                                                  random=random_location,
                                                                  amount=int(background_definition[
                                                                      "vehicle.*"]),
                                                                  category='vehicle')
            configuration_instances_vehicles.append(actor_configuration_instance)

        scenario_configuration.other_actors = configuration_instances_vehicles + \
                                              configuration_instances_walkers


        return BackgroundActivity(self.world, self._ego_actor, scenario_configuration,
                                  cross_factor=cross_factor,
                                  timeout=timeout, debug_mode=False)
    def _extract_vehicle_information(self, obj, rolename, vehicle, args):
        """
        Helper function to _set_actor_information for getting vehicle information from XML tree
        """
        color = None
        model = vehicle.attrib.get('name', "vehicle.*")
        category = vehicle.attrib.get('vehicleCategory', "car")
        ego_vehicle = False
        for prop in obj.iter("Property"):
            if prop.get('name', '') == 'type':
                ego_vehicle = prop.get('value') == 'ego_vehicle'
            if prop.get('name', '') == 'color':
                color = prop.get('value')

        speed = self._get_actor_speed(rolename)
        new_actor = ActorConfigurationData(model,
                                           carla.Transform(),
                                           rolename,
                                           speed,
                                           color=color,
                                           category=category,
                                           args=args)
        new_actor.transform = self._get_actor_transform(rolename)

        if ego_vehicle:
            self.ego_vehicles.append(new_actor)
        else:
            self.other_actors.append(new_actor)
Пример #3
0
    def _extract_pedestrian_information(self, obj, rolename, pedestrian, args):
        """
        Helper function to _set_actor_information for getting pedestrian information from XML tree
        """
        model = pedestrian.attrib.get('model', "walker.*")

        new_actor = ActorConfigurationData(model, carla.Transform(), rolename, category="pedestrian", args=args)
        new_actor.transform = self._get_actor_transform(rolename)

        self.other_actors.append(new_actor)
Пример #4
0
    def _set_actor_information(self):
        """
        Extract all actors and their corresponding specification

        NOTE: The rolename property has to be unique!
        """
        for entity in self.xml_tree.iter("Entities"):
            for obj in entity.iter("Object"):
                rolename = obj.attrib.get('name', 'simulation')
                for vehicle in obj.iter("Vehicle"):
                    color = None
                    model = vehicle.attrib.get('name', "vehicle.*")
                    category = vehicle.attrib.get('category', "car")
                    ego_vehicle = False
                    for prop in obj.iter("Property"):
                        if prop.get('name', '') == 'type':
                            ego_vehicle = prop.get('value') == 'ego_vehicle'
                        if prop.get('name', '') == 'color':
                            color = prop.get('value')

                    speed = self._get_actor_speed(rolename)
                    new_actor = ActorConfigurationData(model,
                                                       carla.Transform(),
                                                       rolename,
                                                       speed,
                                                       color=color,
                                                       category=category)
                    new_actor.transform = self._get_actor_transform(rolename)

                    if ego_vehicle:
                        self.ego_vehicles.append(new_actor)
                    else:
                        self.other_actors.append(new_actor)

                for pedestrian in obj.iter("Pedestrian"):
                    model = pedestrian.attrib.get('model', "walker.*")

                    new_actor = ActorConfigurationData(model,
                                                       carla.Transform(),
                                                       rolename,
                                                       category="pedestrian")
                    new_actor.transform = self._get_actor_transform(rolename)

                    self.other_actors.append(new_actor)

                for misc in obj.iter("MiscObject"):
                    category = misc.attrib.get('category')
                    if category == "barrier":
                        model = "static.prop.streetbarrier"
                    elif category == "guardRail":
                        model = "static.prop.chainbarrier"
                    else:
                        model = misc.attrib.get('name')
                    new_actor = ActorConfigurationData(model,
                                                       carla.Transform(),
                                                       rolename)
                    new_actor.transform = self._get_actor_transform(rolename)

                    self.other_actors.append(new_actor)
Пример #5
0
    def _extract_misc_information(self, obj, rolename, misc, args):
        """
        Helper function to _set_actor_information for getting vehicle information from XML tree
        """
        category = misc.attrib.get('category')
        if category == "barrier":
            model = "static.prop.streetbarrier"
        elif category == "guardRail":
            model = "static.prop.chainbarrier"
        else:
            model = misc.attrib.get('name')
        new_actor = ActorConfigurationData(model, carla.Transform(), rolename, category="misc", args=args)
        new_actor.transform = self._get_actor_transform(rolename)

        self.other_actors.append(new_actor)
Пример #6
0
    def _build_master_scenario(self,
                               world,
                               ego_vehicle,
                               route,
                               town_name,
                               timeout=300,
                               debug_mode=False):
        """
        Create the MasterScenario
        """
        # We have to find the target.
        # we also have to convert the route to the expected format
        master_scenario_configuration = ScenarioConfiguration()
        master_scenario_configuration.target = route[-1][
            0]  # Take the last point and add as target.
        master_scenario_configuration.route = convert_transform_to_location(
            route)
        master_scenario_configuration.town = town_name
        # TODO THIS NAME IS BIT WEIRD SINCE THE EGO VEHICLE  IS ALREADY THERE, IT IS MORE ABOUT THE TRANSFORM
        master_scenario_configuration.ego_vehicle = ActorConfigurationData(
            'vehicle.lincoln.mkz2017', ego_vehicle.get_transform(), 'hero')
        master_scenario_configuration.trigger_points = [
            ego_vehicle.get_transform()
        ]

        # Provide an initial blackboard entry to ensure all scenarios are running correctly
        blackboard = py_trees.blackboard.Blackboard()
        blackboard.set('master_scenario_command', 'scenarios_running')

        return MasterScenario(world, [ego_vehicle],
                              master_scenario_configuration,
                              timeout=timeout,
                              debug_mode=debug_mode)
    def _build_scenario_instances(self, world, ego_vehicle, scenario_definitions, town,
                                  scenarios_per_tick=5, timeout=300, debug_mode=False):
        """
        Based on the parsed route and possible scenarios, build all the scenario classes.
        """
        scenario_instance_vec = []

        if debug_mode:
            for scenario in scenario_definitions:
                loc = carla.Location(scenario['trigger_position']['x'],
                                     scenario['trigger_position']['y'],
                                     scenario['trigger_position']['z']) + carla.Location(z=2.0)
                world.debug.draw_point(loc, size=1.0, color=carla.Color(255, 0, 0), life_time=100000)
                world.debug.draw_string(loc, str(scenario['name']), draw_shadow=False,
                                        color=carla.Color(0, 0, 255), life_time=100000, persistent_lines=True)

        for scenario_number, definition in enumerate(scenario_definitions):
            # Get the class possibilities for this scenario number
            scenario_class = NUMBER_CLASS_TRANSLATION[definition['name']]

            # Create the other actors that are going to appear
            if definition['other_actors'] is not None:
                list_of_actor_conf_instances = self._get_actors_instances(definition['other_actors'])
            else:
                list_of_actor_conf_instances = []
            # Create an actor configuration for the ego-vehicle trigger position

            egoactor_trigger_position = convert_json_to_transform(definition['trigger_position'])
            scenario_configuration = ScenarioConfiguration()
            scenario_configuration.other_actors = list_of_actor_conf_instances
            scenario_configuration.town = town
            scenario_configuration.trigger_points = [egoactor_trigger_position]
            scenario_configuration.subtype = definition['scenario_type']
            scenario_configuration.ego_vehicles = [ActorConfigurationData('vehicle.lincoln.mkz2017',
                                                                          ego_vehicle.get_transform(),
                                                                          'hero')]
            route_var_name = "ScenarioRouteNumber{}".format(scenario_number)
            scenario_configuration.route_var_name = route_var_name

            try:
                scenario_instance = scenario_class(world, [ego_vehicle], scenario_configuration,
                                                   criteria_enable=False, timeout=timeout)
                # Do a tick every once in a while to avoid spawning everything at the same time
                if scenario_number % scenarios_per_tick == 0:
                    sync_mode = world.get_settings().synchronous_mode
                    if sync_mode:
                        world.tick()
                    else:
                        world.wait_for_tick()

                scenario_number += 1
            except Exception as e:      # pylint: disable=broad-except
                if debug_mode:
                    traceback.print_exc()
                print("Skipping scenario '{}' due to setup error: {}".format(definition['name'], e))
                continue

            scenario_instance_vec.append(scenario_instance)

        return scenario_instance_vec
    def _build_background_scenario(self, world, ego_vehicle, town_name, timeout=300, debug_mode=False):
        """
        Create the BackgroundActivity scenario
        """
        scenario_configuration = ScenarioConfiguration()
        scenario_configuration.route = None
        scenario_configuration.town = town_name

        model = 'vehicle.*'
        transform = carla.Transform()

        if town_name == 'Town01' or town_name == 'Town02':
            amount = 120
        elif town_name == 'Town03' or town_name == 'Town05':
            amount = 120
        elif town_name == 'Town04':
            amount = 200
        elif town_name == 'Town06' or town_name == 'Town07':
            amount = 150
        elif town_name == 'Town08':
            amount = 180
        elif town_name == 'Town09':
            amount = 350
        else:
            amount = 0

        actor_configuration_instance = ActorConfigurationData(
            model, transform, rolename='background', autopilot=True, random=True, amount=amount)
        scenario_configuration.other_actors = [actor_configuration_instance]

        return BackgroundActivity(world, [ego_vehicle], scenario_configuration,
                                  timeout=timeout, debug_mode=debug_mode)
Пример #9
0
    def build_scenario_instances(self, scenario_definition_vec, timeout):

        """
            Based on the parsed route and possible scenarios, build all the scenario classes.
        :param scenario_definition_vec: the dictionary defining the scenarios
        :param town: the town where scenarios are going to be
        :return:
        """
        list_instanced_scenarios = []
        if scenario_definition_vec is None:
            return list_instanced_scenarios

        for scenario_name in scenario_definition_vec:
            # The BG activity encapsulates several scenarios that contain vehicles going arround
            if scenario_name == 'background_activity':  # BACKGROUND ACTIVITY SPECIAL CASE

                background_definition = scenario_definition_vec[scenario_name]
                background = self._build_background(background_definition, timeout)

                list_instanced_scenarios.append(background)
            else:

                # Sample the scenarios to be used for this route instance.
                # tehre can be many instances of the same scenario
                scenario_definition_instances = scenario_definition_vec[scenario_name]

                if scenario_definition_instances is None:
                    raise ValueError(" Not Implemented ")

                for scenario_definition in scenario_definition_instances:

                    # TODO scenario 4 is out

                    #ScenarioClass = number_class_translation[scenario_name][0]
                    egoactor_trigger_position = convert_json_to_transform(
                        scenario_definition)
                    scenario_configuration = ScenarioConfiguration()
                    scenario_configuration.other_actors = None  # TODO the other actors are maybe needed
                    scenario_configuration.town = self._town_name
                    scenario_configuration.trigger_point = egoactor_trigger_position
                    scenario_configuration.ego_vehicle = ActorConfigurationData(
                                                            'vehicle.lincoln.mkz2017',
                                                            self._ego_actor.get_transform())
                    try:
                        scenario_instance = ScenarioClass(self.world, self._ego_actor,
                                                          scenario_configuration,
                                                          criteria_enable=False, timeout=timeout)
                    except Exception as e:
                        print("Skipping scenario '{}' due to setup error: {}".format(
                            'Scenario3', e))
                        continue
                    # registering the used actors on the data provider so they can be updated.

                    CarlaDataProvider.register_actors(scenario_instance.other_actors)

                    list_instanced_scenarios.append(scenario_instance)

        return list_instanced_scenarios
Пример #10
0
def convert_json_to_actor(actor_dict):
    """
    Convert a JSON string to an ActorConfigurationData dictionary
    """
    node = ET.Element('waypoint')
    node.set('x', actor_dict['x'])
    node.set('y', actor_dict['y'])
    node.set('z', actor_dict['z'])
    node.set('yaw', actor_dict['yaw'])

    return ActorConfigurationData.parse_from_node(node, 'simulation')
    def _set_actor_information(self):
        """
        Extract all actors and their corresponding specification

        NOTE: The rolename property has to be unique!
        """
        for entity in self.xml_tree.iter("Entities"):
            for obj in entity.iter("Object"):
                rolename = obj.attrib.get('name', 'simulation')
                for vehicle in obj.iter("Vehicle"):
                    model = vehicle.attrib.get('name', "vehicle.*")
                    ego_vehicle = False
                    for prop in obj.iter("Property"):
                        if prop.get('name', '') == 'type':
                            ego_vehicle = prop.get('value') == 'ego_vehicle'

                    new_actor = ActorConfigurationData(model,
                                                       carla.Transform(),
                                                       rolename)
                    new_actor.transform = self._get_actor_transform(rolename)

                    if ego_vehicle:
                        self.ego_vehicles.append(new_actor)
                    else:
                        self.other_actors.append(new_actor)

                for pedestrian in obj.iter("Pedestrian"):
                    model = pedestrian.attrib.get('model', "walker.*")

                    new_actor = ActorConfigurationData(model,
                                                       carla.Transform(),
                                                       rolename)
                    new_actor.transform = self._get_actor_transform(rolename)

                    self.other_actors.append(new_actor)
Пример #12
0
    def build_master_scenario(self, route, town_name, timeout, terminate_on_collision):
        # We have to find the target.
        # we also have to convert the route to the expected format
        master_scenario_configuration = ScenarioConfiguration()
        master_scenario_configuration.target = route[-1][0]  # Take the last point and add as target.
        master_scenario_configuration.route = convert_transform_to_location(route)

        master_scenario_configuration.town = town_name
        master_scenario_configuration.ego_vehicle = ActorConfigurationData('vehicle.lincoln.mkz2017',
                                                                           self._ego_actor.get_transform())
        master_scenario_configuration.trigger_point = self._ego_actor.get_transform()
        CarlaDataProvider.register_actor(self._ego_actor)

        return MasterScenario(self.world, [self._ego_actor], master_scenario_configuration,
                              timeout=timeout, terminate_on_collision=terminate_on_collision)
Пример #13
0
    def _build_scenario_instances(self,
                                  world,
                                  ego_vehicle,
                                  scenario_definitions,
                                  town,
                                  timeout=300,
                                  debug_mode=False):
        """
        Based on the parsed route and possible scenarios, build all the scenario classes.
        """
        scenario_instance_vec = []

        if debug_mode:
            for scenario in scenario_definitions:
                loc = carla.Location(
                    scenario['trigger_position']['x'],
                    scenario['trigger_position']['y'],
                    scenario['trigger_position']['z']) + carla.Location(z=2.0)
                world.debug.draw_point(loc,
                                       size=1.0,
                                       color=carla.Color(255, 0, 0),
                                       life_time=100000)
                world.debug.draw_string(loc,
                                        str(scenario['name']),
                                        draw_shadow=False,
                                        color=carla.Color(0, 0, 255),
                                        life_time=100000,
                                        persistent_lines=True)

        for definition in scenario_definitions:
            # Get the class possibilities for this scenario number
            possibility_vec = NUMBER_CLASS_TRANSLATION[definition['name']]

            scenario_class = possibility_vec[definition['type']]

            # Create the other actors that are going to appear
            if definition['other_actors'] is not None:
                list_of_actor_conf_instances = self._get_actors_instances(
                    definition['other_actors'])
            else:
                list_of_actor_conf_instances = []
            # Create an actor configuration for the ego-vehicle trigger position

            egoactor_trigger_position = convert_json_to_transform(
                definition['trigger_position'])
            scenario_configuration = ScenarioConfiguration()
            scenario_configuration.other_actors = list_of_actor_conf_instances
            scenario_configuration.town = town
            scenario_configuration.trigger_points = [egoactor_trigger_position]
            scenario_configuration.ego_vehicles = [
                ActorConfigurationData('vehicle.lincoln.mkz2017',
                                       ego_vehicle.get_transform(), 'hero')
            ]
            try:
                scenario_instance = scenario_class(world, [ego_vehicle],
                                                   scenario_configuration,
                                                   criteria_enable=False,
                                                   timeout=timeout)
            except Exception as e:
                print("Skipping scenario '{}' due to setup error: {}".format(
                    definition['name'], e))
                continue

            scenario_instance_vec.append(scenario_instance)

        return scenario_instance_vec
    def parse_scenario_configuration(scenario_config_file, scenario_name):
        """
        Parse scenario configuration file and provide a list of
        ScenarioConfigurations @return

        If scenario_name starts with "group:" all scenarios within
        the config file will be returned. Otherwise only the scenario,
        that matches the scenario_name.
        """

        single_scenario_only = True
        if scenario_name.startswith("group:"):
            single_scenario_only = False
            scenario_name = scenario_name[6:]

        tree = ET.parse(scenario_config_file)

        scenario_configurations = []

        for scenario in tree.iter("scenario"):

            new_config = ScenarioConfiguration()
            new_config.town = scenario.attrib.get('town', None)
            new_config.name = scenario.attrib.get('name', None)
            new_config.type = scenario.attrib.get('type', None)
            new_config.other_actors = []
            new_config.ego_vehicles = []
            new_config.trigger_points = []

            for weather in scenario.iter("weather"):
                new_config.weather.cloudiness = float(
                    weather.attrib.get("cloudiness", 0))
                new_config.weather.precipitation = float(
                    weather.attrib.get("precipitation", 0))
                new_config.weather.precipitation_deposits = float(
                    weather.attrib.get("precipitation_deposits", 0))
                new_config.weather.wind_intensity = float(
                    weather.attrib.get("wind_intensity", 0.35))
                new_config.weather.sun_azimuth_angle = float(
                    weather.attrib.get("sun_azimuth_angle", 0.0))
                new_config.weather.sun_altitude_angle = float(
                    weather.attrib.get("sun_altitude_angle", 15.0))
                new_config.weather.fog_density = float(
                    weather.attrib.get("fog_density", 0.0))
                new_config.weather.fog_distance = float(
                    weather.attrib.get("fog_distance", 0.0))
                new_config.weather.wetness = float(
                    weather.attrib.get("wetness", 0.0))

            for ego_vehicle in scenario.iter("ego_vehicle"):

                new_config.ego_vehicles.append(
                    ActorConfigurationData.parse_from_node(
                        ego_vehicle, 'hero'))
                new_config.trigger_points.append(
                    new_config.ego_vehicles[-1].transform)

            for target in scenario.iter("target"):
                new_config.target = TargetConfiguration(target)

            for route in scenario.iter("route"):
                route_conf = RouteConfiguration()
                route_conf.parse_xml(route)
                new_config.route = route_conf

            for other_actor in scenario.iter("other_actor"):
                new_config.other_actors.append(
                    ActorConfigurationData.parse_from_node(
                        other_actor, 'scenario'))

            if single_scenario_only:
                if new_config.name == scenario_name:
                    scenario_configurations.append(new_config)
            else:
                scenario_configurations.append(new_config)

        return scenario_configurations