コード例 #1
0
    def reset(self, prev_step_info=None):
        """Reset Method. To be called at the end of each episode"""
        if self.initial_reset:
            while self.ob is None:
                try:
                    self.client = snakeoil3.Client(p=self.port,
                                                   vision=self.vision,
                                                   visualise=self.visualise)
                    # Open new UDP in vtorcs
                    self.client.MAX_STEPS = self.CLIENT_MAX_STEPS
                    self.client.get_servers_input(step=0)
                    # Get the initial input from torcs
                    raw_ob = self.client.S.d
                    # Get the current full-observation
                    self.ob = self.make_observation(raw_ob)
                except:
                    pass
            self.initial_reset = False

        else:
            try:
                self.ob, self.client = TorcsEnv.reset(self,
                                                      client=self.client,
                                                      relaunch=True)
            except Exception as e:
                self.ob = None
                while self.ob is None:
                    try:
                        print("Hard Reset")
                        # self.end(self.client)
                        self.client = snakeoil3.Client(p=self.port,
                                                       vision=self.vision)
                        # Open new UDP in vtorcs
                        self.client.MAX_STEPS = self.CLIENT_MAX_STEPS
                        self.client.get_servers_input(step=0)
                        # Get the initial input from torcs
                        raw_ob = self.client.S.d
                        # Get the current full-observation from torcs
                        self.ob = self.make_observation(raw_ob)
                    except:
                        pass

        self.distance_traversed = 0
        s_t = np.hstack((self.ob.angle, self.ob.track, self.ob.trackPos,
                         self.ob.speedX, self.ob.speedY, self.ob.speedZ,
                         self.ob.wheelSpinVel / 100.0, self.ob.rpm))

        self.prev_angle = 0.0
        self.prev_dist = 0.0
        self.prev_lane = 0.0
        self.accel_PID.reset_pid()
        self.steer_PID.reset_pid()
        return s_t
コード例 #2
0
ファイル: gym_madras.py プロジェクト: trhoangdung/MADRaS
    def reset(self):
        """Reset Method to be called at the end of each episode."""
        self.step_num = 0
        if not self.initial_reset:
            self.torcs_server_config.generate_torcs_server_config()
            self.madras_agent_port = self.torcs_server_port + self.torcs_server_config.num_traffic_cars
            self.client.port = self.madras_agent_port  # This is very bad code! But we wont need it any way in v2
            logging.info("Num traffic cars in server {}".format(
                self.torcs_server_config.num_traffic_cars))

        if self._config.traffic:
            self.traffic_manager.reset(
                self.torcs_server_config.num_traffic_cars)

        self._config.track_len = self.torcs_server_config.track_length

        if self.initial_reset:
            self.wait_for_observation()
            self.initial_reset = False

        else:
            while True:
                try:
                    self.ob, self.client = TorcsEnv.reset(self,
                                                          client=self.client,
                                                          relaunch=True)
                except Exception:
                    self.wait_for_observation()

                if not np.any(np.asarray(self.ob.track) < 0):
                    break
                else:
                    logging.info(
                        "Reset: Reset failed as agent started off track. Retrying..."
                    )

        self.distance_traversed = 0
        s_t = self.observation_handler.get_obs(self.ob, self._config)
        if self._config.pid_assist:
            self.PID_controller.reset()
        self.reward_handler.reset()
        self.done_handler.reset()
        logging.info("Reset: Starting new episode")
        if np.any(np.asarray(self.ob.track) < 0):
            logging.info("Reset produced bad track values.")
        return s_t
コード例 #3
0
def playTraffic(port=3101, target_vel=50.0, angle=0.0, sleep=0):
    """Traffic Play function."""
    env = TorcsEnv(vision=False, throttle=True, gear_change=False)
    ob = None
    while ob is None:
        try:
            client = snakeoil3.Client(p=port, vision=False)
            client.MAX_STEPS = np.inf
            client.get_servers_input(step=0)
            obs = client.S.d
            ob = env.make_observation(obs)
        except:
            pass
    episode_count = cfg['traffic']['max_eps']
    max_steps = cfg['traffic']['max_steps_eps']
    early_stop = 0
    velocity_i = target_vel / 300.0
    accel_pid = PID(np.array([10.5, 0.05, 2.8]))
    steer_pid = PID(np.array([5.1, 0.001, 0.000001]))
    steer = 0.0
    accel = 0.0
    brake = 0
    A = cfg['traffic']['amplitude'] / 300.0
    T = cfg['traffic']['time_period']
    # print(velocity_i)
    for i in range(episode_count):
        info = {'termination_cause': 0}
        steer = 0.0
        accel = 0.0
        brake = 0
        S = 0.0
        for step in range(max_steps):
            a_t = np.asarray([steer, accel, brake])  # [steer, accel, brake]
            try:
                ob, r_t, done, info = env.step(step, client, a_t, early_stop)
                if done:
                    pass
            except Exception as e:
                print("Exception caught at point A at port " + str(i) + str(e))
                ob = None
                while ob is None:
                    try:
                        client = snakeoil3.Client(p=port, vision=False)
                        client.MAX_STEPS = np.inf
                        client.get_servers_input(step=0)
                        obs = client.S.d
                        ob = env.make_observation(obs)
                    except:
                        pass
                    continue
            if (step <= sleep):
                print("WAIT" + str(port))
                continue
            velocity = velocity_i + A * math.sin(step / T)
            opp = ob.opponents
            front = np.array([opp[15], opp[16], opp[17], opp[18], opp[19]])
            closest_front = np.min(front)
            if (step % T == 0):
                print("VEL_CHANGE: ", velocity * 300.0)
            vel_error = velocity - ob.speedX
            angle_error = -(ob.trackPos - angle) / 10 + ob.angle
            steer_pid.update_error(angle_error)
            accel_pid.update_error(vel_error)
            accel = accel_pid.output()
            steer = steer_pid.output()
            if accel < 0:
                brake = 1
            else:
                brake = 0
            if closest_front < ((float(0.5 * ob.speedX * 100) + 10.0) / 200.0):
                brake = 1
            else:
                brake = 0

        try:
            if 'termination_cause' in info.keys() and info['termination_cause'] == 'hardReset':
                print('Hard reset by some agent')
                ob, client = env.reset(client=client, relaunch=True)

        except Exception as e:
            print("Exception caught at point B at port " + str(i) + str(e) )
            ob = None
            while ob is None:
                try:
                    client = snakeoil3.Client(p=port, vision=False)  # Open new UDP in vtorcs
                    client.MAX_STEPS = np.inf
                    client.get_servers_input(0)  # Get the initial input from torcs
                    obs = client.S.d  # Get the current full-observation from torcs
                    ob = env.make_observation(obs)
                except:
                    print("Exception caught at at point C at port " + str(i) + str(e))