Esempio n. 1
0
    def _load_and_wait_for_world(self, args, town, ego_vehicles=None):
        """
        Load a new CARLA world and provide data to CarlaDataProvider
        """

        self.world = self.client.load_world(town)
        settings = self.world.get_settings()
        settings.fixed_delta_seconds = 1.0 / self.frame_rate
        settings.synchronous_mode = True
        self.world.apply_settings(settings)

        self.world.reset_all_traffic_lights()

        CarlaDataProvider.set_client(self.client)
        CarlaDataProvider.set_world(self.world)
        CarlaDataProvider.set_traffic_manager_port(args.traffic_manager_port)

        self.traffic_manager.set_synchronous_mode(True)
        self.traffic_manager.set_random_device_seed(args.traffic_manager_seed)
        self.traffic_manager.set_hybrid_physics_mode(True)

        # Wait for the world to be ready
        if CarlaDataProvider.is_sync_mode():
            self.world.tick()
        else:
            self.world.wait_for_tick()

        if CarlaDataProvider.get_map().name != town:
            raise Exception("The CARLA server uses the wrong map!"
                            "This scenario requires to use map {}".format(town))
Esempio n. 2
0
    def test_all_xosc(self):
        """
        Load all examples OpenSCENARIO files
        """
        all_test_files = glob.glob('**/srunner/examples/*.xosc',
                                   recursive=True)

        for filename in all_test_files:
            client = carla.Client()
            config = OpenScenarioConfiguration(filename, client, {})
            self.assertTrue(config is not None)
            CarlaDataProvider.set_client(client)
            ego_vehicles = []
            for vehicle in config.ego_vehicles:
                ego_vehicles.append(
                    CarlaDataProvider.request_new_actor(
                        vehicle.model,
                        vehicle.transform,
                        vehicle.rolename,
                        color=vehicle.color,
                        actor_category=vehicle.category))

            scenario = OpenScenario(world=client.get_world(),
                                    ego_vehicles=ego_vehicles,
                                    config=config,
                                    config_file=filename,
                                    timeout=100000)
            self.assertTrue(scenario is not None)

            CarlaDataProvider.cleanup()
Esempio n. 3
0
    def _load_and_wait_for_world(self, town, ego_vehicles=None):
        """
        Load a new CARLA world and provide data to CarlaDataProvider
        """

        if self._args.reloadWorld:
            self.world = self.client.load_world(town)
        else:
            # if the world should not be reloaded, wait at least until all ego vehicles are ready
            ego_vehicle_found = False
            if self._args.waitForEgo:
                while not ego_vehicle_found and not self._shutdown_requested:
                    vehicles = self.client.get_world().get_actors().filter(
                        'vehicle.*')
                    for ego_vehicle in ego_vehicles:
                        ego_vehicle_found = False
                        for vehicle in vehicles:
                            if vehicle.attributes[
                                    'role_name'] == ego_vehicle.rolename:
                                ego_vehicle_found = True
                                break
                        if not ego_vehicle_found:
                            print("Not all ego vehicles ready. Waiting ... ")
                            time.sleep(1)
                            break

        self.world = self.client.get_world()

        if self._args.sync:
            settings = self.world.get_settings()
            settings.synchronous_mode = True
            settings.fixed_delta_seconds = 1.0 / self.frame_rate
            self.world.apply_settings(settings)

            self.traffic_manager.set_synchronous_mode(True)
            self.traffic_manager.set_random_device_seed(
                int(self._args.trafficManagerSeed))

        CarlaDataProvider.set_client(self.client)
        CarlaDataProvider.set_world(self.world)
        CarlaDataProvider.set_traffic_manager_port(
            int(self._args.trafficManagerPort))

        # Wait for the world to be ready
        if CarlaDataProvider.is_sync_mode():
            self.world.tick()
        else:
            self.world.wait_for_tick()
        if CarlaDataProvider.get_map(
        ).name != town and CarlaDataProvider.get_map().name != "OpenDriveMap":
            print("The CARLA server uses the wrong map: {}".format(
                CarlaDataProvider.get_map().name))
            print("This scenario requires to use map: {}".format(town))
            return False

        return True
Esempio n. 4
0
    def __init__(self, args):
        """
        Setup CARLA client and world
        Setup ScenarioManager
        """
        self._args = args

        if args.timeout:
            self.client_timeout = float(args.timeout)

        # First of all, we need to create the client that will send the requests
        # to the simulator. Here we'll assume the simulator is accepting
        # requests in the localhost at port 2000.
        self.client = carla.Client(args.host, int(args.port))
        self.client.set_timeout(self.client_timeout)
        CarlaDataProvider.set_client(self.client)

        dist = pkg_resources.get_distribution("carla")
        if LooseVersion(dist.version) < LooseVersion('0.9.11'):
            raise ImportError("CARLA version 0.9.11 or newer required. CARLA version found: {}".format(dist))

        # Load agent if requested via command line args
        # If something goes wrong an exception will be thrown by importlib (ok here)
        if self._args.agent is not None:
            module_name = os.path.basename(args.agent).split('.')[0]
            sys.path.insert(0, os.path.dirname(args.agent))
            self.module_agent = importlib.import_module(module_name)

        # Create the ScenarioManager
        self.manager = ScenarioManager(self._args.debug, self._args.sync, self._args.timeout)

        # Create signal handler for SIGINT
        self._shutdown_requested = False
        if sys.platform != 'win32':
            signal.signal(signal.SIGHUP, self._signal_handler)
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        self._start_wall_time = datetime.now()
Esempio n. 5
0
    def __init__(self, client, vehicle_model, route, sensors,
                 scenario_definitions, exp_params, agent_name):
        """
        The experience is like a instance of the environment
         contains all the objects (vehicles, sensors) and scenarios of the the current experience
        :param vehicle_model: the model that is going to be used to spawn the ego CAR
        """

        # We save the agent name for data savings
        self._agent_name = agent_name

        # save all the experiment parameters to be used later
        self._exp_params = exp_params
        # carla recorder mode save the full carla logs to do some replays
        if self._exp_params['carla_recording']:
            client.start_recorder('env_{}_number_{}_batch_{:0>4d}.log'.format(
                self._exp_params['env_name'], self._exp_params['env_number'],
                self._exp_params['exp_number']))
        # this parameter sets all the sensor threads and the main thread into saving data
        self._save_data = exp_params['save_data']
        # we can also toogle if we want to save sensors or not.
        self._save_sensors = exp_params['save_sensors']
        # Start objects that are going to be created
        self.world = None
        # You try to reconnect a few times.
        self.MAX_CONNECTION_ATTEMPTS = 7
        # Scenario definitions to perform the scenario building
        self.scenario_definitions = scenario_definitions
        self._ego_actor = None
        self._instanced_sensors = []
        # set the client object connected to the
        self._client = client
        # We also set the town name to be used
        self._town_name = exp_params['town_name']

        self._vehicle_model = vehicle_model
        # if data is being saved we create the writer object

        # if we are going to save, we keep track of a dictionary with all the data
        self._writer = Writer(exp_params['package_name'],
                              exp_params['env_name'],
                              exp_params['env_number'],
                              exp_params['exp_number'],
                              agent_name,
                              other_vehicles=exp_params['save_opponents'],
                              walkers=exp_params['save_walkers'])

        self._environment_data = {
            'exp_measurements':
            None,  # The exp measurements are specific of the experience
            'ego_controls': None,
            'scenario_controls': None
        }
        # identify this exp
        self._exp_id = self._exp_params['exp_number']

        # We try running all the necessary initalization, if we fail we clean the
        try:
            # Sensor interface, a buffer that contains all the read sensors
            self._sensor_interface = SensorInterface(
                number_threads_barrier=len(sensors))
            # Load the world
            self._load_world()
            # Set the actor pool so the scenarios can prepare themselves when needed
            CarlaDataProvider.set_client(client)
            CarlaDataProvider.set_world(self.world)
            # Set the world for the global data provider
            CarlaDataProvider.set_world(self.world)
            # We get the lat lon ref that is important for the route
            self._lat_ref, self._lon_ref = _get_latlon_ref(self.world)
            # We instance the ego actor object
            _, self._route = interpolate_trajectory(self.world, route)
            # elevate the z transform to avoid spawning problems
            elevate_transform = self._route[0][0]
            elevate_transform.location.z += 0.5
            self._spawn_ego_car(elevate_transform)
            # We setup all the instanced sensors
            self._setup_sensors(sensors, self._ego_actor)
            # We set all the traffic lights to green to avoid having this traffic scenario.
            self._reset_map()
            # Data for building the master scenario
            self._timeout = estimate_route_timeout(self._route)
            self._master_scenario = self.build_master_scenario(
                self._route, exp_params['town_name'], self._timeout)
            other_scenarios = self.build_scenario_instances(
                scenario_definitions, self._timeout)
            self._list_scenarios = [self._master_scenario] + other_scenarios
            # Route statistics, when the route is finished there will
            # be route statistics on this object. and nothing else
            self._route_statistics = None
            # We tick the world to have some starting points
            self.tick_world()
        except RuntimeError as r:
            # We clean the dataset if there is any exception on creation
            traceback.print_exc()
            if self._save_data:
                self._clean_bad_dataset()
            # Re raise the exception
            raise r
Esempio n. 6
0
    try:
        # set the world and data_provider
        client = carla.Client(host, port)
        client.set_timeout(2.0)

        world = client.load_world(city_name)
        traffic_manager = client.get_trafficmanager(int(trafficManagerPort))

        settings = world.get_settings()
        settings.synchronous_mode = True
        settings.fixed_delta_seconds = 1.0 / frame_rate
        world.apply_settings(settings)

        traffic_manager.set_synchronous_mode(True)
        traffic_manager.set_random_device_seed(int(trafficManagerSeed))
        CarlaDataProvider.set_client(client)
        CarlaDataProvider.set_world(world)
        CarlaDataProvider.set_traffic_manager_port(int(trafficManagerPort))

        if CarlaDataProvider.is_sync_mode():
            world.tick()
        else:
            world.wait_for_tick()

        # generate ego vehicle
        blueprint_library = world.get_blueprint_library()
        bp = random.choice(blueprint_library.filter('vehicle'))

        if bp.has_attribute('color'):
            color = random.choice(bp.get_attribute('color').recommended_values)
            bp.set_attribute('color', color)