
"""
The MIT License

Copyright (c) 2021 MatNet

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import torch
from logging import getLogger

from FFSPEnv import FFSPEnv as Env
from FFSPModel import FFSPModel as Model

from torch.optim import Adam as Optimizer
from torch.optim.lr_scheduler import MultiStepLR as Scheduler

from utils import *


class FFSPTrainer:
    def __init__(self,
                 env_params,
                 model_params,
                 optimizer_params,
                 trainer_params):

        # save arguments
        self.env_params = env_params
        self.model_params = model_params
        self.optimizer_params = optimizer_params
        self.trainer_params = trainer_params

        # result folder, logger
        self.logger = getLogger(name='trainer')
        self.result_folder = get_result_folder()
        self.result_log = LogData()

        self.latent_cont_dim = self.model_params['latent_cont_size']
        self.latent_disc_dim = self.model_params['latent_disc_size']
        
        # cuda
        USE_CUDA = self.trainer_params['use_cuda']
        if USE_CUDA:
            cuda_device_num = self.trainer_params['cuda_device_num']
            torch.cuda.set_device(cuda_device_num)
            device = torch.device('cuda', cuda_device_num)
            torch.set_default_tensor_type('torch.cuda.FloatTensor')
        else:
            device = torch.device('cpu')
            torch.set_default_tensor_type('torch.FloatTensor')

        # Main Components
        self.model = Model(**self.model_params)
        self.env = Env(**self.env_params)
        self.optimizer = Optimizer(self.model.parameters(), **self.optimizer_params['optimizer'])
        self.scheduler = Scheduler(self.optimizer, **self.optimizer_params['scheduler'])
        # restore
        self.start_epoch = 1
        model_load = trainer_params['model_load']
        if model_load['enable']:
            checkpoint_fullname = '{path}/checkpoint-{epoch}.pt'.format(**model_load)
            checkpoint = torch.load(checkpoint_fullname, map_location=device)
            self.model.load_state_dict(checkpoint['model_state_dict'], strict=False)
            if not model_load['load_model_only']:
                print("Set the previous learning process")
                self.start_epoch = 1 + model_load['epoch']
                self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
                self.scheduler.last_epoch = model_load['epoch']-1
            self.logger.info('Saved Model Loaded !!')

        # utility
        self.time_estimator = TimeEstimator()
        self.loop_size = self.trainer_params['train_episodes']//self.trainer_params['train_batch_size']
        self.accumulation_step = self.trainer_params['accumulation_step']
    
    def run(self):
        self.time_estimator.reset(self.start_epoch)
        self.model.train()
        for epoch in range(self.start_epoch, self.trainer_params['epochs']+1):
            self.logger.info('=================================================================')
            score_AM = AverageMeter()
            loss_AM = AverageMeter()
            loop_cnt=0
            for episode in range(self.loop_size):
                batch_size = self.trainer_params['train_batch_size']
                self.env.load_problems(batch_size)
                reset_state, _, _ = self.env.reset()
                latent_c_var = torch.empty(batch_size, self.env.pomo_size, self.latent_cont_dim ).uniform_(-1, 1)

                latent_d_var = torch.zeros((batch_size, self.env.pomo_size, self.latent_disc_dim), dtype=torch.float32)
                one_hot_idx = torch.randint(0, self.latent_disc_dim, (batch_size, self.env.pomo_size), dtype=torch.long)
                latent_d_var[torch.arange(batch_size).unsqueeze(1), torch.arange(self.env.pomo_size).unsqueeze(0), one_hot_idx] = 1

                latent_var = torch.cat([latent_d_var, latent_c_var], dim=-1)
                self.model.pre_forward(reset_state, latent_var)

                prob_list = torch.zeros(size=(batch_size, self.env.pomo_size, 0))
                state, reward, done = self.env.pre_step()
                while not done:
                    selected, prob = self.model(state)
                    state, reward, done = self.env.step(selected)
                    prob_list = torch.cat((prob_list, prob[:, :, None]), dim=2)
                reward = reward.float()
                ##############################################
                max_reward = reward.max(dim=1, keepdim=True).values
                mean_reward = reward.mean(dim=1, keepdim=True)
                pomo_variance = reward.var(dim=1, keepdim=True, unbiased=False)
                loss_weight = (max_reward - mean_reward) / torch.sqrt(pomo_variance + 1e-8)

                max_pomo_reward, argmax = reward.max(dim=1)
                probs = prob_list[torch.arange(batch_size), argmax, :] 
                probs = probs[:,:-1]
                log_probs = torch.log(probs+ 1e-8)

                batch_loss = log_probs*loss_weight
                loss = -batch_loss.mean()

                loss.backward()
                if (episode+1)%self.accumulation_step==0 or (episode+1)==self.loop_size:
                    self.optimizer.step()
                    self.optimizer.zero_grad()

                max_pomo_reward, _ = reward.max(dim=1)
                score_mean = -max_pomo_reward.float().mean()  
                score_AM.update(score_mean.item(), batch_size)
                loss_AM.update(loss.item()*self.accumulation_step, batch_size) 

                if epoch == self.start_epoch:
                    loop_cnt += 1
                    if loop_cnt <= 10:
                        self.logger.info('Epoch {:3d}: Train {:3d}/{:3d}({:1.1f}%)  Score: {:.4f},  Loss: {:.4f}'
                                        .format(epoch, (episode+1)*batch_size, self.trainer_params['train_episodes'], 100. * (episode+1)*batch_size / self.trainer_params['train_episodes'],
                                                score_AM.avg, loss_AM.avg))
            self.scheduler.step()
            # Train
            self.result_log.append('train_score', epoch, score_AM.avg)
            self.result_log.append('train_loss', epoch, loss_AM.avg)

            ############################
            # Logs & Checkpoint
            ############################
            elapsed_time_str, remain_time_str = self.time_estimator.get_est_string(epoch, self.trainer_params['epochs'])
            self.logger.info("Epoch {:3d}/{:3d}: Time Est.: Elapsed[{}], Remain[{}]".format(
                epoch, self.trainer_params['epochs'], elapsed_time_str, remain_time_str))
            self.logger.info('Epoch {:3d}:  Trian set Score: {:.4f},  CE Loss: {:.4f}'.format(epoch, score_AM.avg, loss_AM.avg))
            all_done = (epoch == self.trainer_params['epochs'])
            model_save_interval = self.trainer_params['logging']['model_save_interval']

            if all_done or (epoch % model_save_interval) == 0:
                checkpoint_dict = {
                    'epoch': epoch,
                    'model_state_dict': self.model.state_dict(),
                    'optimizer_state_dict': self.optimizer.state_dict(),
                    'scheduler_state_dict': self.scheduler.state_dict(),
                    'result_log': self.result_log.get_raw_data()
                }
                torch.save(checkpoint_dict, '{}/checkpoint-{}.pt'.format(self.result_folder, epoch))

            if all_done:
                self.logger.info(" *** Training Done *** ")
                self.logger.info("Now, printing log array...")
                util_print_log_array(self.logger, self.result_log)