예제 #1
0
class Agent():
    """Interacts with and learns from the environment."""
    def __init__(self, state_size, action_size, seed, model="QNetwork"):
        """Initialize an Agent object.

        Params
        ======
            state_size (int): dimension of each state
            action_size (int): dimension of each action
            seed (int): random seed
        """
        self.state_size = state_size
        self.action_size = action_size
        self.seed = random.seed(seed)

        # Q-Network
        if model == "QNetwork":
            self.qnetwork_local = QNetwork(state_size, action_size,
                                           seed).to(device)
            self.qnetwork_target = QNetwork(state_size, action_size,
                                            seed).to(device)

        if model == "QNetworkConvolutional":
            self.qnetwork_local = QNetworkConvolutional(
                state_size, action_size, seed).to(device)
            self.qnetwork_target = QNetworkConvolutional(
                state_size, action_size, seed).to(device)

        if model == "DuelingDQN":
            self.qnetwork_local = DuelingDQN(state_size, action_size,
                                             seed).to(device)
            self.qnetwork_target = DuelingDQN(state_size, action_size,
                                              seed).to(device)

        print("Model: " + model)

        self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)

        # Replay memory
        self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)

        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0

    def step(self, state, action, reward, next_state, done):
        # Save experience in replay memory
        self.memory.add(state, action, reward, next_state, done)

        # Learn every UPDATE_EVERY time steps.
        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            # If enough samples are available in memory, get random subset and learn
            if len(self.memory) > BATCH_SIZE:
                experiences = self.memory.sample()
                self.learn(experiences, GAMMA)

    def act(self, state, eps=0.):
        """Returns actions for given state as per current policy.

        Params
        ======
            state (array_like): current state
            eps (float): epsilon, for epsilon-greedy action selection
        """
        state = torch.from_numpy(state).float().unsqueeze(0).to(device)
        self.qnetwork_local.eval()
        with torch.no_grad():
            action_values = self.qnetwork_local(state)
        self.qnetwork_local.train()

        # Epsilon-greedy action selection
        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy())
        else:
            return random.choice(np.arange(self.action_size))

    def learn(self, experiences, gamma):
        """Update value parameters using given batch of experience tuples.

        Params
        ======
            experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples
            gamma (float): discount factor
        """
        states, actions, rewards, next_states, dones = experiences

        # Get max predicted Q values (for next states) from target model
        Q_targets_next = self.qnetwork_target(next_states).detach().max(
            1)[0].unsqueeze(1)
        # Compute Q targets for current states
        Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))

        # Get expected Q values from local model
        Q_expected = self.qnetwork_local(states).gather(1, actions)

        # Compute loss
        loss = F.mse_loss(Q_expected, Q_targets)
        # Minimize the loss
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        # ------------------- update target network ------------------- #
        self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)

    def soft_update(self, local_model, target_model, tau):
        """Soft update model parameters.
        θ_target = τ*θ_local + (1 - τ)*θ_target

        Params
        ======
            local_model (PyTorch model): weights will be copied from
            target_model (PyTorch model): weights will be copied to
            tau (float): interpolation parameter
        """
        for target_param, local_param in zip(target_model.parameters(),
                                             local_model.parameters()):
            target_param.data.copy_(tau * local_param.data +
                                    (1.0 - tau) * target_param.data)
class Agent():
    """Interacts with and learns from the environment."""
    def __init__(self, state_size, action_size, seed, max_t=1000):
        """Initialize an Agent object.

        Params
        ======
            state_size (int): dimension of each state
            action_size (int): dimension of each action
            seed (int): random seed
        """
        self.state_size = state_size
        self.action_size = action_size
        self.seed = random.seed(seed)

        # Q-Network
        self.qnetwork_local = DuelingDQN(state_size, action_size,
                                         seed).to(device)
        self.qnetwork_target = DuelingDQN(state_size, action_size,
                                          seed).to(device)
        self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)

        # Replay memory
        self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)
        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0
        self.prio_b = PRIO_B
        self.b_step = 0
        self.max_b_step = 2000
        self.learnFirst = True

    def step(self, state, action, reward, next_state, done):
        # Save experience in replay memory
        #self.memory.add(state, action, reward, next_state, done)

        # Hassan : Save the experience in prioritized replay memory
        self.memory.prio_add(state, action, reward, next_state, done)

        # Learn every UPDATE_EVERY time steps.
        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            # If enough samples are available in memory, get random subset and learn
            if len(self.memory) > BATCH_SIZE:
                #experiences = self.memory.sample()
                #self.learn(experiences, GAMMA)

                # Hassan : prioritized replay memory

                self.b_step = self.b_step + 1
                experiences, indices = self.memory.prio_sample()
                self.learn(experiences, GAMMA, indices)

    def act(self, state, eps=0.):
        """Returns actions for given state as per current policy.

        Params
        ======
            state (array_like): current state
            eps (float): epsilon, for epsilon-greedy action selection
        """
        state = torch.from_numpy(state).float().unsqueeze(0).to(device)
        self.qnetwork_local.eval()
        with torch.no_grad():
            action_values = self.qnetwork_local(state)
        self.qnetwork_local.train()

        # Epsilon-greedy action selection
        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy())
        else:
            return random.choice(np.arange(self.action_size))

    def get_beta(self, t):
        '''
        Return the current exponent β based on its schedul. Linearly anneal β
        from its initial value β0 to 1, at the end of learning.
        :param t: integer. Current time step in the episode
        :return current_beta: float. Current exponent beta
        '''
        #f_frac = min(float(t) / self.max_b_step, 1.0)
        #current_beta = self.prio_b + f_frac * (1. - self.prio_b)
        #current_beta = min(1,current_beta)
        self.prio_b = min(1, self.prio_b + PRIO_B_INC)
        return self.prio_b

    def learn(self, experiences, gamma, indices):
        """Update value parameters using given batch of experience tuples.

        Params
        ======
            experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples
            gamma (float): discount factor
        """
        states, actions, rewards, next_states, dones, probabilities = experiences

        ## TODO: compute and minimize the loss
        "*** YOUR CODE HERE ***"

        # Get max predicted Q values (for next states) from target model
        # Hassan : Action is selected using greedy policy
        #Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1)

        # Hassan : Double DQN
        # Selecting actions which maximizes while taking w (qnetwork_local)
        next_actions = self.qnetwork_local(next_states).detach().argmax(
            dim=1).unsqueeze(1)
        #next_actions_test = self.qnetwork_local(next_states).detach().max(1)[1].unsqueeze(1) # Hassan : from the example
        #print(torch.sum(next_actions-next_actions_test)) # Hassan : no difference found
        # Selecting q values of these actions using w' (qnetwork_target)
        Q_targets_next = self.qnetwork_target(next_states).gather(
            1, next_actions)

        # Compute Q targets for current states
        # Hassan : This is TD Target
        Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))

        # Get expected Q values from local model
        # Hassan : This is current value
        Q_expected = self.qnetwork_local(states).gather(1, actions)

        #Hassan : Compute the td_error
        td_error = Q_targets - Q_expected
        #print(td_error.detach().numpy())
        #self.prio_b = min(1, PRIO_B_INC+self.prio_b)
        f_currbeta = self.get_beta(0)
        #print(f_currbeta)
        #f_currbeta = self.get_beta(self.b_step)
        #print(self.b_step)

        #print(t)
        #print(self.prio_b)
        weights_importance = probabilities.mul_(
            self.memory.__len__()).pow_(-f_currbeta)
        #  Hassan : calculate max_weights_importance
        #probabilities_min = min(self.memory.priorities)/self.memory.cum_priorities
        probabilities_min = self.memory.min_priority / self.memory.cum_priorities
        max_weights_importance = (probabilities_min *
                                  self.memory.__len__())**(-f_currbeta)
        # Hassan : divide the weights importance with the max_weights_importance
        # Hassan : Improvement why not calculating the max_weights_importance = max(weights_importance)??
        # Hassan : this will only calculating on the current list not the complete one

        #print(weights_importance)
        #print(weights_importance.max(0)[0])
        #print(max_weights_importance)
        #if self.learnFirst:
        #    self.learnFirst = False
        #else :
        #    max_weights_importance = max_weights_importance[0]

        weights_final = weights_importance.div_(max_weights_importance)

        square_weighted_error = td_error.pow_(2).mul_(weights_final)
        loss = square_weighted_error.mean()

        # Hassan : after the observations observation from example, update was done after the weights calculation
        if self.prio_b > 0.5:
            self.memory.prio_update(indices,
                                    td_error.detach().numpy(), PRIO_E, PRIO_A)

        # Compute loss
        #loss = F.mse_loss(Q_expected, Q_targets)
        # Minimize the loss
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        # ------------------- update target network ------------------- #
        # Hassan : Here not after C steps w is changed though cahnged slightly after every learn step
        # Hassan : We can modify to change this after ever C steps
        self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)

    def soft_update(self, local_model, target_model, tau):
        """Soft update model parameters.
        θ_target = τ*θ_local + (1 - τ)*θ_target

        Params
        ======
            local_model (PyTorch model): weights will be copied from
            target_model (PyTorch model): weights will be copied to
            tau (float): interpolation parameter
        """
        for target_param, local_param in zip(target_model.parameters(),
                                             local_model.parameters()):
            target_param.data.copy_(tau * local_param.data +
                                    (1.0 - tau) * target_param.data)
예제 #3
0
class Agent():
    """Interacts with and learns from the environment."""
    def __init__(self, state_size, action_size, seed):
        """Initialize an Agent object.
        
        Params
        ======
            state_size (int): dimension of each state
            action_size (int): dimension of each action
            seed (int): random seed
        """
        self.state_size = state_size
        self.action_size = action_size
        self.seed = random.seed(seed)

        # Q-Network
        self.qnetwork_local = DuelingDQN(state_size, action_size,
                                         seed).to(device)
        self.qnetwork_target = DuelingDQN(state_size, action_size,
                                          seed).to(device)
        self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)

        self.priority_alpha = 0.0  #current best: 03
        self.priority_beta_start = 0.4
        self.priority_beta_frames = BUFFER_SIZE

        # Replay memory
        self.memory = PrioritizedReplayMemory(BUFFER_SIZE, self.priority_alpha,
                                              self.priority_beta_start,
                                              self.priority_beta_frames)
        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0

    def step(self, state, action, reward, next_state, done):
        # Save experience in replay memory
        self.memory.push((state, action, reward, next_state, done))

        # Learn every UPDATE_EVERY time steps.
        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            # If enough samples are available in memory, get random subset and learn
            if self.memory.storage_size() > BATCH_SIZE:
                #print("storage == ", self.memory.storage_size())
                experiences, idxes, weights = self.memory.sample(BATCH_SIZE)
                self.learn(experiences, idxes, weights, GAMMA)

    def act(self, state, eps=0.):
        """Returns actions for given state as per current policy.
        
        Params
        ======
            state (array_like): current state
            eps (float): epsilon, for epsilon-greedy action selection
        """
        state = torch.from_numpy(state).float().unsqueeze(0).to(device)
        self.qnetwork_local.eval()
        with torch.no_grad():
            action_values = self.qnetwork_local(state)
        self.qnetwork_local.train()

        # Epsilon-greedy action selection
        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy())
        else:
            return random.choice(np.arange(self.action_size))

    def learn(self, experiences, idxes, weights, gamma):
        """Update value parameters using given batch of experience tuples.

        Params
        ======
            experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples 
            gamma (float): discount factor
        """
        states, actions, rewards, next_states, dones = zip(*experiences)

        states = torch.from_numpy(
            np.vstack([state for state in states
                       if state is not None])).float().to(device)
        actions = torch.from_numpy(
            np.vstack([action for action in actions
                       if action is not None])).long().to(device)
        rewards = torch.from_numpy(
            np.vstack([reward for reward in rewards
                       if reward is not None])).float().to(device)
        next_states = torch.from_numpy(
            np.vstack([
                next_state for next_state in next_states
                if next_state is not None
            ])).float().to(device)
        dones = torch.from_numpy(
            np.vstack([done for done in dones if done is not None
                       ]).astype(np.uint8)).float().to(device)

        # Get max predicted Q values (for next states) from target model
        #print("state-action values:")
        #print(self.qnetwork_target(next_states).detach())
        #print(next_states)
        next_target_Q = self.qnetwork_target.forward(next_states)
        #print("next_target_Q == ", next_target_Q)

        _, next_local_Q_index = torch.max(
            self.qnetwork_local.forward(next_states), axis=1)

        #Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1)

        Q_targets_next = next_target_Q[range(next_target_Q.shape[0]),
                                       next_local_Q_index]

        Q_targets_next1 = Q_targets_next.reshape((len(Q_targets_next), 1))

        # Compute Q targets for current states
        Q_targets = rewards + (gamma * Q_targets_next1 * (1 - dones))

        # Get expected Q values from local model
        Q_expected = self.qnetwork_local(states).gather(1, actions)

        #print(Q_expected)
        #print(Q_targets)

        diff = Q_expected - Q_targets
        #print(diff)
        #diff = diff.mean()
        #print(idxes)
        #print(diff.detach().squeeze().abs().cpu().numpy().tolist())
        #update the priority of the replay buffer

        self.memory.update_priorities(
            idxes,
            diff.detach().squeeze().abs().cpu().numpy().tolist())

        # Compute loss
        loss = F.mse_loss(Q_expected, Q_targets) * weights
        loss = loss.mean()

        # Minimize the loss
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        # ------------------- update target network ------------------- #
        self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)

    def soft_update(self, local_model, target_model, tau):
        """Soft update model parameters.
        θ_target = τ*θ_local + (1 - τ)*θ_target

        Params
        ======
            local_model (PyTorch model): weights will be copied from
            target_model (PyTorch model): weights will be copied to
            tau (float): interpolation parameter 
        """
        for target_param, local_param in zip(target_model.parameters(),
                                             local_model.parameters()):
            target_param.data.copy_(tau * local_param.data +
                                    (1.0 - tau) * target_param.data)
예제 #4
0
class Agent():
    """Interacts with and learns from the environment."""

    def __init__(self, state_size, action_size, seed,max_t=1000):
        """Initialize an Agent object.

        Params
        ======
            state_size (int): dimension of each state
            action_size (int): dimension of each action
            seed (int): random seed
        """
        self.state_size = state_size
        self.action_size = action_size
        self.seed = random.seed(seed)

        # Q-Network
        self.qnetwork_local = DuelingDQN(state_size, action_size, seed).to(device)
        self.qnetwork_target = DuelingDQN(state_size, action_size, seed).to(device)
        self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)

        # Replay memory
        self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)
        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0
        self.prio_b = PRIO_B
        self.b_step = 0
        self.max_b_step = 2000
        self.learnFirst = True

    def step(self, state, action, reward, next_state, done):

        # Hassan : Save the experience in prioritized replay memory
        self.memory.prio_add(state, action, reward, next_state, done)

        # Learn every UPDATE_EVERY time steps.
        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            # If enough samples are available in memory, get random subset and learn
            if len(self.memory) > BATCH_SIZE:

                self.b_step = self.b_step + 1
                experiences, indices = self.memory.prio_sample()
                self.learn(experiences, GAMMA, indices)


    def act(self, state, eps=0.):
        """Returns actions for given state as per current policy.

        Params
        ======
            state (array_like): current state
            eps (float): epsilon, for epsilon-greedy action selection
        """
        state = torch.from_numpy(state).float().unsqueeze(0).to(device)
        self.qnetwork_local.eval()
        with torch.no_grad():
            action_values = self.qnetwork_local(state)
        self.qnetwork_local.train()

        # Epsilon-greedy action selection
        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy())
        else:
            return random.choice(np.arange(self.action_size))

    def get_beta(self, t):
        '''
        Return the current exponent β based on its schedul. Linearly anneal β
        from its initial value β0 to 1, at the end of learning.
        :param t: integer. Current time step in the episode
        :return current_beta: float. Current exponent beta
        '''
        #f_frac = min(float(t) / self.max_b_step, 1.0)
        #current_beta = self.prio_b + f_frac * (1. - self.prio_b)
        #current_beta = min(1,current_beta)
        self.prio_b = min(1,self.prio_b + PRIO_B_INC)
        return self.prio_b

    def learn(self, experiences, gamma, indices):
        """Update value parameters using given batch of experience tuples.

        Params
        ======
            experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples
            gamma (float): discount factor
        """
        states, actions, rewards, next_states, dones, probabilities = experiences

        "*** YOUR CODE HERE ***"

        # Double DQN implementation
        # Selecting actions which maximizes while taking w (qnetwork_local)
        next_actions = self.qnetwork_local(next_states).detach().argmax(dim=1).unsqueeze(1)

        # evluate best actions using w' (qnetwork_target)
        Q_targets_next = self.qnetwork_target(next_states).gather(1, next_actions)


        # Compute Q targets for current states (TD Target)
        Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))

        # Get expected Q values from local model
        Q_expected = self.qnetwork_local(states).gather(1, actions)

        # Compute the td_error
        td_error = Q_targets - Q_expected


        f_currbeta = self.get_beta(0)

        # Prioritized experience replay : calculating the final weights for calculating loss function
        weights_importance = probabilities.mul_(self.memory.__len__()).pow_(-f_currbeta)
        probabilities_min = self.memory.min_priority/self.memory.cum_priorities
        max_weights_importance = (probabilities_min * self.memory.__len__())**(-f_currbeta)
        weights_final = weights_importance.div_(max_weights_importance)

        # Compute mean squared weighted error
        square_weighted_error = td_error.pow_(2).mul_(weights_final)
        loss = square_weighted_error.mean()

        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        #  Prioritized experience replay : updating the priority of experience tuple in replay buffer
        self.memory.prio_update(indices,td_error.detach().numpy(),PRIO_E,PRIO_A)

        # ------------------- update target network ------------------- #
        self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)

    def soft_update(self, local_model, target_model, tau):
        """Soft update model parameters.
        θ_target = τ*θ_local + (1 - τ)*θ_target

        Params
        ======
            local_model (PyTorch model): weights will be copied from
            target_model (PyTorch model): weights will be copied to
            tau (float): interpolation parameter
        """
        for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
            target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
class Agent:
    """Interacts with and learns from the environment."""
    def __init__(self, config):
        """Initialize an Agent object"""
        self.seed = random.seed(config["general"]["seed"])
        self.config = config

        # Q-Network
        self.q = DuelingDQN(config).to(DEVICE)
        self.q_target = DuelingDQN(config).to(DEVICE)

        self.optimizer = optim.RMSprop(self.q.parameters(),
                                       lr=config["agent"]["learning_rate"])
        self.criterion = F.mse_loss

        self.memory = ReplayBuffer(config)
        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0

    def save_experiences(self, state, action, reward, next_state, done):
        """Prepare and save experience in replay memory"""
        reward = np.clip(reward, -1.0, 1.0)
        self.memory.add(state, action, reward, next_state, done)

    def _current_step_is_a_learning_step(self):
        """Check if the current step is an update step"""
        self.t_step = (self.t_step + 1) % self.config["agent"]["update_rate"]
        return self.t_step == 0

    def _enough_samples_in_memory(self):
        """Check if minimum amount of samples are in memory"""
        return len(self.memory) > self.config["train"]["batch_size"]

    def epsilon_greedy_action_selection(self, action_values, eps):
        """Epsilon-greedy action selection"""
        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy())
        else:
            return random.choice(
                np.arange(self.config["general"]["action_size"]))

    def act(self, state, eps=0.0):
        """Returns actions for given state as per current policy"""
        state = torch.from_numpy(state).float().unsqueeze(0).to(DEVICE)
        self.q.eval()
        with torch.no_grad():
            action_values = self.q(state)
        self.q.train()

        return self.epsilon_greedy_action_selection(action_values, eps)

    def _calc_loss(self, states, actions, rewards, next_states, dones):
        """Calculates loss for a given experience batch"""
        q_eval = self.q(states).gather(1, actions)
        q_eval_next = self.q(next_states)
        _, q_argmax = q_eval_next.detach().max(1)
        q_next = self.q_target(next_states)
        q_next = q_next.gather(1, q_argmax.unsqueeze(1))
        q_target = rewards + (self.config["agent"]["gamma"] * q_next *
                              (1 - dones))
        loss = self.criterion(q_eval, q_target)
        return loss

    def _update_weights(self, loss):
        """update the q network weights"""
        torch.nn.utils.clip_grad.clip_grad_value_(self.q.parameters(), 1.0)
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

    def learn(self):
        """Update network using one sample of experience from memory"""
        if self._current_step_is_a_learning_step(
        ) and self._enough_samples_in_memory():
            states, actions, rewards, next_states, dones = self.memory.sample(
                self.config["train"]["batch_size"])
            loss = self._calc_loss(states, actions, rewards, next_states,
                                   dones)
            self._update_weights(loss)
            self._soft_update(self.q, self.q_target)

    def _soft_update(self, local_model, target_model):
        """Soft update target network parameters: θ_target = τ*θ_local + (1 - τ)*θ_target"""
        for target_param, local_param in zip(target_model.parameters(),
                                             local_model.parameters()):
            target_param.data.copy_(
                self.config["agent"]["tau"] * local_param.data +
                (1.0 - self.config["agent"]["tau"]) * target_param.data)

    def save(self):
        """Save the network weights"""
        helper.mkdir(
            os.path.join(".", *self.config["general"]["checkpoint_dir"],
                         self.config["general"]["env_name"]))
        current_date_time = helper.get_current_date_time()
        current_date_time = current_date_time.replace(" ", "__").replace(
            "/", "_").replace(":", "_")

        torch.save(
            self.q.state_dict(),
            os.path.join(".", *self.config["general"]["checkpoint_dir"],
                         self.config["general"]["env_name"],
                         "ckpt_" + current_date_time))

    def load(self):
        """Load latest available network weights"""
        list_of_files = glob.glob(
            os.path.join(".", *self.config["general"]["checkpoint_dir"],
                         self.config["general"]["env_name"], "*"))
        latest_file = max(list_of_files, key=os.path.getctime)
        self.q.load_state_dict(torch.load(latest_file))
        self.q_target.load_state_dict(torch.load(latest_file))
class Agent():
    """Interacts with and learns from the environment."""

    def __init__(self,
                 state_size,
                 action_size,
                 seed,
                 gamma=GAMMA,
                 buffer_size=BUFFER_SIZE,
                 batch_size=BATCH_SIZE,
                 update_every=UPDATE_EVERY,
                 lr=LR,
                 tau=TAU
    ):
        """Initialize an Agent object.
        
        Params
        ======
            state_size (int): dimension of each state
            action_size (int): dimension of each action
            seed (int): random seed
        """
        self.state_size = state_size
        self.action_size = action_size
        self.seed = random.seed(seed)
        self.gamma = gamma
        self.batch_size = batch_size

        # Q-Network
        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        self.model_local = DuelingDQN(state_size, action_size, seed).to(self.device)
        self.model_target = DuelingDQN(state_size, action_size, seed).to(self.device)
        self.optimizer = optim.Adam(self.model_local.parameters(), lr=LR)
    
        # Replay memory
        self.memory = ReplayBuffer(
            action_size=action_size,
            buffer_size=BUFFER_SIZE,
            batch_size=BATCH_SIZE,
            seed=seed,
            device=self.device
        )
        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0
    
    def step(self, state, action, reward, next_state, done):
        # Save experience in replay memory
        self.memory.add(state, action, reward, next_state, done)
        
        # Learn every UPDATE_EVERY time steps.
        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            # If enough samples are available in memory, get random subset and learn
            if len(self.memory) > self.batch_size:
                experiences = self.memory.sample()
                self.update(experiences)

    def act(self, state, eps=0.):
        """Returns actions for given state as per current policy.
        
        Params
        ======
            state (array_like): current state
            eps (float): epsilon, for epsilon-greedy action selection
        """
        state = torch.FloatTensor(state).float().unsqueeze(0).to(self.device)
        
        self.model_local.eval()
        with torch.no_grad():
            qvals = self.model_local.forward(state)
        self.model_local.train()
        
        # Epsilon-greedy action selection
        if random.random() > eps:
            action = np.argmax(qvals.cpu().detach().numpy())
            return action
        else:
            return random.choice(np.arange(self.action_size))
    

    def update(self, batch):
        """Update value parameters using given batch of experience tuples.

        Params
        ======
            batch (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples 
            gamma (float): discount factor
        """
        states, actions, rewards, next_states, dones = batch
        
        # Get expected Q values from local model
        curr_Q = self.model_local.forward(states).gather(1, actions)
#         curr_Q = curr_Q.squeeze(1)
        
        # Get max predicted Q values (for next states) from target model
        max_next_Q = self.model_target.forward(next_states).detach().max(1)[0].unsqueeze(1)
        expected_Q = rewards + (self.gamma * max_next_Q * (1 - dones))

        loss = F.mse_loss(curr_Q, expected_Q)

        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()
        
        # update target model
        self.update_target(self.model_local, self.model_target, TAU)     
    def update_target(self, local_model, target_model, tau):
        """Soft update model parameters.
        θ_target = τ*θ_local + (1 - τ)*θ_target

        Params
        ======
            local_model (PyTorch model): weights will be copied from
            target_model (PyTorch model): weights will be copied to
            tau (float): interpolation parameter 
        """
        for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
            target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)