import torch.nn as nn
import torch.nn.functional as F


class RNNAgent(nn.Module):
    def __init__(self, input_shape, args):
        super(RNNAgent, self).__init__()
        self.args = args

        self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
        self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)
        if not args.levin_flag_quantile:
            self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)
        else:
            self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions * args.N_QUANT)

    def init_hidden(self):
        # make hidden states on same device as model
        # 主要是在 controllers 中使用
        return self.fc1.weight.new(1, self.args.rnn_hidden_dim).zero_()

    def forward(self, inputs, hidden_state):
        mb_size = inputs.size(0)
        x = F.relu(self.fc1(inputs))
        h_in = hidden_state.reshape(-1, self.args.rnn_hidden_dim)
        h = self.rnn(x, h_in)
        if not self.args.levin_flag_quantile:
            q = self.fc2(h)
        else:
            q = self.fc2(h).view(mb_size, self.args.n_actions, self.args.N_QUANT)
        return q, h
