import argparse
import os
import random
import shutil
import time
import warnings

import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
from torch.utils.tensorboard import SummaryWriter
from attribution_methods.our.model import resnet,vgg
from attribution_methods.our import networks as nw
import numpy as np
import torch.nn.functional as F
import matplotlib.pyplot as plt
RESNET=True
THIRD=True
DATASET='test'#'train'#
#method=['Saliency']
#method=['our_fullgrad']#,
#method=['our_method']
#method=['CAMERAS']
#method=['DeepLIFT']
#method=['our_method_minus_mean',]
#method=['Saliency','InputXGradient','DeepLIFT']#
#method=['IntegratedGradients']#,'random'
method=['Our_GBP']
#method=['FullGrad']
#method=['GradCAM']
WIDTH=16
torch.set_num_threads(4)
print(RESNET,method,WIDTH)
os.environ["CUDA_VISIBLE_DEVICES"] = "5"
model_names = sorted(name for name in models.__dict__
    if name.islower() and not name.startswith("__")
    and callable(models.__dict__[name]))

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--data', metavar='DIR',default='/data_SSD2/zgh/workspace/data/ImageNet',
                    help='path to dataset')
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50',
                    choices=model_names,
                    help='model architecture: ' +
                        ' | '.join(model_names) +
                        ' (default: resnet18)')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
                    help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=90, type=int, metavar='N',
                    help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                    help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=8, type=int,
                    metavar='N',
                    help='mini-batch size (default: 256), this is the total '
                         'batch size of all GPUs on the current node when '
                         'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
                    metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                    help='momentum')
parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,
                    metavar='W', help='weight decay (default: 1e-4)',
                    dest='weight_decay')
parser.add_argument('-p', '--print-freq', default=10, type=int,
                    metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
                    help='path to latest checkpoint (default: none)')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
                    help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
                    help='use pre-trained model')
parser.add_argument('--world-size', default=-1, type=int,
                    help='number of nodes for distributed training')
parser.add_argument('--rank', default=-1, type=int,
                    help='node rank for distributed training')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
                    help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='nccl', type=str,
                    help='distributed backend')
parser.add_argument('--seed', default=None, type=int,
                    help='seed for initializing training. ')
parser.add_argument('--gpu', default=None, type=int,
                    help='GPU id to use.')
parser.add_argument('--multiprocessing-distributed', action='store_true',
                    help='Use multi-processing distributed training to launch '
                         'N processes per node, which has N GPUs. This is the '
                         'fastest way to use PyTorch for either single node or '
                         'multi node data parallel training')

def main():
    args = parser.parse_args()

    if args.seed is not None:
        random.seed(args.seed)
        torch.manual_seed(args.seed)
        cudnn.deterministic = True
        warnings.warn('You have chosen to seed training. '
                      'This will turn on the CUDNN deterministic setting, '
                      'which can slow down your training considerably! '
                      'You may see unexpected behavior when restarting '
                      'from checkpoints.')

    if args.gpu is not None:
        warnings.warn('You have chosen a specific GPU. This will completely '
                      'disable data parallelism.')

    if args.dist_url == "env://" and args.world_size == -1:
        args.world_size = int(os.environ["WORLD_SIZE"])

    args.distributed = args.world_size > 1 or args.multiprocessing_distributed

    ngpus_per_node = torch.cuda.device_count()
    if args.multiprocessing_distributed:
        # Since we have ngpus_per_node processes per node, the total world_size
        # needs to be adjusted accordingly
        args.world_size = ngpus_per_node * args.world_size
        # Use torch.multiprocessing.spawn to launch distributed processes: the
        # main_worker process function
        mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))
    else:
        # Simply call main_worker function
        main_worker(args.gpu, ngpus_per_node, args)


def main_worker(gpu, ngpus_per_node, args):
    global best_acc1
    args.gpu = gpu

    if args.gpu is not None:
        print("Use GPU: {} for training".format(args.gpu))

    if args.distributed:
        if args.dist_url == "env://" and args.rank == -1:
            args.rank = int(os.environ["RANK"])
        if args.multiprocessing_distributed:
            # For multiprocessing distributed training, rank needs to be the
            # global rank among all the processes
            args.rank = args.rank * ngpus_per_node + gpu
        dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
                                world_size=args.world_size, rank=args.rank)
    # create model

    if RESNET:
        model=resnet.resnet50(pretrained=True)
    else:
        model=vgg.vgg16_bn(pretrained=True)
    if not torch.cuda.is_available():
        print('using CPU, this will be slow')
    else:
        #torch.cuda.set_device(args.gpu)
        model = model.cuda()
        model.eval()

    cudnn.benchmark = True

    traindir = os.path.join(args.data, 'train')
    valdir = os.path.join(args.data, 'val')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])
    '''
    train_dataset = datasets.ImageFolder(
        traindir,
        transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            normalize,
        ]))
    if args.distributed:
        train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
    else:
        train_sampler = None
    train_loader = torch.utils.data.DataLoader(
        train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
        num_workers=args.workers, pin_memory=True, sampler=train_sampler)
    '''
    val_loader = torch.utils.data.DataLoader(
        datasets.ImageFolder(valdir, transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            normalize,
        ])),
        batch_size=args.batch_size, shuffle=True,
        num_workers=args.workers, pin_memory=True)

    results=[]
    ACC=[]
    model.eval()
    K=5
    import ADGT
    adgt = ADGT.ADGT(use_cuda=True, name='ImageNet')
    if DATASET=='train':
        loader=None
    else:
        loader=val_loader
    if True:
        end = time.time()
        for i, (images, target) in enumerate(loader):
            images, target = images.cuda(), target.cuda()
            with torch.no_grad():
                base=model(images)
                base=F.softmax(base,1)
                top1=torch.argmax(base,1)
                ACC.append((top1==target).float().cpu())
            for m in method:
                heatmaps=adgt.pure_explain(images,model,m).detach()
                results.append(EBPG(F.relu(heatmaps).detach()).cpu())
            if i%10==0:
                print(i,results[i],ACC[i])

    results=torch.cat(tuple(results),0)
    ACC=torch.cat(tuple(ACC),0)

    right=results[ACC==1]
    wrong=results[ACC==0]
    if not os.path.exists(method[0]):
        os.mkdir(method[0])
    np.save(method[0]+'/right_'+str(RESNET)+str(WIDTH)+'.npy',right.numpy())
    np.save(method[0]+'/wrong_' + str(RESNET) + str(WIDTH) + '.npy', wrong.numpy())
    right=right.clamp(0,1)
    wrong=wrong.clamp(0,1)
    print(right.size(), wrong.size(), results.max())
    '''
    plt.hist(right.numpy(),color='blue')
    plt.hist(wrong.numpy(),color='red')
    if not os.path.exists('result'):
        os.mkdir('result')
    plt.savefig('result/hist_'+str(RESNET)+str(WIDTH)+'.png')
    plt.close()
    '''
from sklearn.metrics import roc_curve,auc
def ROC_AUC(right,wrong):
    right=np.nan_to_num(right)
    wrong=np.nan_to_num(wrong)
    right0=1-right
    wrong0=1-wrong
    yr=np.ones_like(right0)
    yw=np.zeros_like(wrong0)
    y_test=np.concatenate((yr,yw))
    y_score=np.concatenate((right0,wrong0))
    fpr,tpr,thrd=roc_curve(y_test,y_score)
    auc_score=auc(fpr,tpr)
    print(auc_score)
    plt.plot(fpr,tpr,label='ROC curve ( area = %0.4f )' % auc_score)
    plt.plot([0,1],[0,1],linestyle='--')
    plt.xlim([0, 1])
    plt.ylim([0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend(loc='lower right')
    if not os.path.exists('result'):
        os.mkdir('result')
    plt.savefig('result/'+method[0]+str(RESNET)+str(WIDTH)+'.jpg')
    plt.close()

def TOP_ROC_AUC(right,wrong,p=50):
    right=np.nan_to_num(right)
    wrong=np.nan_to_num(wrong)
    right0=1-right
    wrong0=1-wrong
    yr=np.ones_like(right0)
    yw=np.zeros_like(wrong0)
    y_test=np.concatenate((yr,yw))
    y_score=np.concatenate((right0,wrong0))
    temp=np.percentile(y_score,100-p)
    y_test,y_score=y_test[y_score<temp],y_score[y_score<temp]
    fpr,tpr,thrd=roc_curve(y_test,y_score)
    auc_score=auc(fpr,tpr)
    print(auc_score)
    plt.plot(fpr,tpr,label='ROC curve ( area = %0.4f )' % auc_score)
    plt.plot([0,1],[0,1],linestyle='--')
    plt.xlim([0, 1])
    plt.ylim([0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend(loc='lower right')
    if not os.path.exists('result'):
        os.mkdir('result')
    plt.savefig('result/top_'+method[0]+str(RESNET)+str(WIDTH)+'.jpg')
    plt.close()

def EBPG(heatmaps,width=WIDTH):
    mask=torch.zeros_like(heatmaps)
    mask[:,:,:width,:]=1
    mask[:,:,mask.size(2)-width:,:]=1
    mask[:, :, :,:width] = 1
    mask[:, :, :,mask.size(3) - width:] = 1
    result=torch.sum((heatmaps*mask).view(heatmaps.size(0),-1),1)/(torch.sum(heatmaps.view(heatmaps.size(0),-1),1)+1e-8)
    return result

if __name__ == '__main__':
    main()
    right=np.load(method[0]+'/right_'+str(RESNET)+str(WIDTH)+'.npy')
    wrong=np.load(method[0]+'/wrong_' + str(RESNET) + str(WIDTH) + '.npy')
    #ROC_AUC(right,wrong)
    TOP_ROC_AUC(right, wrong)