import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from functools import partial
import logging
import os

try:
    from . import initializer
    from .utils import load_state
except: 
    import initializer
    from utils import load_state

__all__ = ['ResNeXt', 'resnet50', 'resnet101']


def conv3x3x3(in_planes, out_planes, stride=1):
    # 3x3x3 convolution with padding
    return nn.Conv3d(
        in_planes,
        out_planes,
        kernel_size=3,
        stride=stride,
        padding=1,
        bias=False)


def conv1x1x1(in_planes, out_planes, stride=1):
    return nn.Conv3d(in_planes,
                     out_planes,
                     kernel_size=1,
                     stride=stride,
                     bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1, downsample=None):
        super().__init__()

        self.conv1 = conv3x3x3(in_planes, planes, stride)
        self.bn1 = nn.BatchNorm3d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3x3(planes, planes)
        self.bn2 = nn.BatchNorm3d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, in_planes, planes, stride=1, downsample=None):
        super().__init__()

        self.conv1 = conv1x1x1(in_planes, planes)
        self.bn1 = nn.BatchNorm3d(planes)
        self.conv2 = conv3x3x3(planes, planes, stride)
        self.bn2 = nn.BatchNorm3d(planes)
        self.conv3 = conv1x1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm3d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self,
                 block,
                 layers,
                 block_inplanes=[64, 128, 256, 512],
                 n_input_channels=3,
                 conv1_t_size=7,
                 conv1_t_stride=1,
                 no_max_pool=False,
                 shortcut_type='B',
                 widen_factor=1.0,
                 num_classes=400, 
                 pretrained=True):
        super().__init__()

        block_inplanes = [int(x * widen_factor) for x in block_inplanes]

        self.in_planes = block_inplanes[0]
        self.no_max_pool = no_max_pool

        self.conv1 = nn.Conv3d(n_input_channels,
                               self.in_planes,
                               kernel_size=(conv1_t_size, 7, 7),
                               stride=(conv1_t_stride, 2, 2),
                               padding=(conv1_t_size // 2, 3, 3),
                               bias=False)
        self.bn1 = nn.BatchNorm3d(self.in_planes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool3d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, block_inplanes[0], layers[0],
                                       shortcut_type)
        self.layer2 = self._make_layer(block,
                                       block_inplanes[1],
                                       layers[1],
                                       shortcut_type,
                                       stride=2)
        self.layer3 = self._make_layer(block,
                                       block_inplanes[2],
                                       layers[2],
                                       shortcut_type,
                                       stride=2)
        self.layer4 = self._make_layer(block,
                                       block_inplanes[3],
                                       layers[3],
                                       shortcut_type,
                                       stride=2)

        self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1))
        self.fc = nn.Linear(block_inplanes[3] * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv3d):
                nn.init.kaiming_normal_(m.weight,
                                        mode='fan_out',
                                        nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm3d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

         # Initialization

        initializer.xavier(net=self)

        if pretrained:
            pretrained_model=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'pretrained/resnet-101-kinetics.pth')
            logging.info("Network:: graph initialized, loading pretrained model: `{}'".format(pretrained_model))
            assert os.path.exists(pretrained_model), "cannot locate: `{}'".format(pretrained_model)
            pretrained = torch.load(pretrained_model)
            load_state(self, pretrained['state_dict'])
        else:
            logging.info("Network:: graph initialized, use random inilization!")

    def _downsample_basic_block(self, x, planes, stride):
        out = F.avg_pool3d(x, kernel_size=1, stride=stride)
        zero_pads = torch.zeros(out.size(0), planes - out.size(1), out.size(2),
                                out.size(3), out.size(4))
        if isinstance(out.data, torch.cuda.FloatTensor):
            zero_pads = zero_pads.cuda()

        out = torch.cat([out.data, zero_pads], dim=1)

        return out

    def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
        downsample = None
        if stride != 1 or self.in_planes != planes * block.expansion:
            if shortcut_type == 'A':
                downsample = partial(self._downsample_basic_block,
                                     planes=planes * block.expansion,
                                     stride=stride)
            else:
                downsample = nn.Sequential(
                    conv1x1x1(self.in_planes, planes * block.expansion, stride),
                    nn.BatchNorm3d(planes * block.expansion))

        layers = []
        layers.append(
            block(in_planes=self.in_planes,
                  planes=planes,
                  stride=stride,
                  downsample=downsample))
        self.in_planes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.in_planes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        if not self.no_max_pool:
            x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return x


def get_fine_tuning_parameters(model, ft_begin_index):
    if ft_begin_index == 0:
        return model.parameters()

    ft_module_names = []
    for i in range(ft_begin_index, 5):
        ft_module_names.append('layer{}'.format(i))
    ft_module_names.append('fc')

    parameters = []
    for k, v in model.named_parameters():
        for ft_module in ft_module_names:
            if ft_module in k:
                parameters.append({'params': v})
                break
        else:
            parameters.append({'params': v, 'lr': 0.0})

    return parameters

def RESNET101(**kwargs):
    """Constructs a ResNet-50 model.
    """
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
    return model

if __name__ == "__main__":
    import torch
    logging.getLogger().setLevel(logging.DEBUG)
    # ---------
    net1 = RESNET101(num_classes=11, pretrained=True)
    data = torch.randn(1,3,16,224,224)
    output1 = net1(data)
    print (output1.shape)

[((451, 540), 'torch.nn.Conv3d', 'nn.Conv3d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=3, stride=stride, padding=1,\n    bias=False)\n', (460, 540), True, 'import torch.nn as nn\n'), ((647, 721), 'torch.nn.Conv3d', 'nn.Conv3d', (['in_planes', 'out_planes'], {'kernel_size': '(1)', 'stride': 'stride', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n', (656, 721), True, 'import torch.nn as nn\n'), ((8449, 8480), 'torch.randn', 'torch.randn', (['(1)', '(3)', '(16)', '(224)', '(224)'], {}), '(1, 3, 16, 224, 224)\n', (8460, 8480), False, 'import torch\n'), ((1031, 1053), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['planes'], {}), '(planes)\n', (1045, 1053), True, 'import torch.nn as nn\n'), ((1074, 1095), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1081, 1095), True, 'import torch.nn as nn\n'), ((1162, 1184), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['planes'], {}), '(planes)\n', (1176, 1184), True, 'import torch.nn as nn\n'), ((1818, 1840), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['planes'], {}), '(planes)\n', (1832, 1840), True, 'import torch.nn as nn\n'), ((1915, 1937), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['planes'], {}), '(planes)\n', (1929, 1937), True, 'import torch.nn as nn\n'), ((2021, 2060), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['(planes * self.expansion)'], {}), '(planes * self.expansion)\n', (2035, 2060), True, 'import torch.nn as nn\n'), ((2081, 2102), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2088, 2102), True, 'import torch.nn as nn\n'), ((3248, 3412), 'torch.nn.Conv3d', 'nn.Conv3d', (['n_input_channels', 'self.in_planes'], {'kernel_size': '(conv1_t_size, 7, 7)', 'stride': '(conv1_t_stride, 2, 2)', 'padding': '(conv1_t_size // 2, 3, 3)', 'bias': '(False)'}), '(n_input_channels, self.in_planes, kernel_size=(conv1_t_size, 7, 7\n    ), stride=(conv1_t_stride, 2, 2), padding=(conv1_t_size // 2, 3, 3),\n    bias=False)\n', (3257, 3412), True, 'import torch.nn as nn\n'), ((3578, 3608), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['self.in_planes'], {}), '(self.in_planes)\n', (3592, 3608), True, 'import torch.nn as nn\n'), ((3629, 3650), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3636, 3650), True, 'import torch.nn as nn\n'), ((3674, 3722), 'torch.nn.MaxPool3d', 'nn.MaxPool3d', ([], {'kernel_size': '(3)', 'stride': '(2)', 'padding': '(1)'}), '(kernel_size=3, stride=2, padding=1)\n', (3686, 3722), True, 'import torch.nn as nn\n'), ((4648, 4679), 'torch.nn.AdaptiveAvgPool3d', 'nn.AdaptiveAvgPool3d', (['(1, 1, 1)'], {}), '((1, 1, 1))\n', (4668, 4679), True, 'import torch.nn as nn\n'), ((4698, 4757), 'torch.nn.Linear', 'nn.Linear', (['(block_inplanes[3] * block.expansion)', 'num_classes'], {}), '(block_inplanes[3] * block.expansion, num_classes)\n', (4707, 4757), True, 'import torch.nn as nn\n'), ((5176, 5204), 'initializer.xavier', 'initializer.xavier', ([], {'net': 'self'}), '(net=self)\n', (5194, 5204), False, 'import initializer\n'), ((5844, 5889), 'torch.nn.functional.avg_pool3d', 'F.avg_pool3d', (['x'], {'kernel_size': '(1)', 'stride': 'stride'}), '(x, kernel_size=1, stride=stride)\n', (5856, 5889), True, 'import torch.nn.functional as F\n'), ((6141, 6180), 'torch.cat', 'torch.cat', (['[out.data, zero_pads]'], {'dim': '(1)'}), '([out.data, zero_pads], dim=1)\n', (6150, 6180), False, 'import torch\n'), ((7158, 7180), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (7171, 7180), True, 'import torch.nn as nn\n'), ((5486, 5518), 'os.path.exists', 'os.path.exists', (['pretrained_model'], {}), '(pretrained_model)\n', (5500, 5518), False, 'import os\n'), ((5592, 5620), 'torch.load', 'torch.load', (['pretrained_model'], {}), '(pretrained_model)\n', (5602, 5620), False, 'import torch\n'), ((5633, 5675), 'utils.load_state', 'load_state', (['self', "pretrained['state_dict']"], {}), "(self, pretrained['state_dict'])\n", (5643, 5675), False, 'from utils import load_state\n'), ((5702, 5770), 'logging.info', 'logging.info', (['"""Network:: graph initialized, use random inilization!"""'], {}), "('Network:: graph initialized, use random inilization!')\n", (5714, 5770), False, 'import logging\n'), ((8324, 8343), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (8341, 8343), False, 'import logging\n'), ((4849, 4919), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['m.weight'], {'mode': '"""fan_out"""', 'nonlinearity': '"""relu"""'}), "(m.weight, mode='fan_out', nonlinearity='relu')\n", (4872, 4919), True, 'import torch.nn as nn\n'), ((6439, 6528), 'functools.partial', 'partial', (['self._downsample_basic_block'], {'planes': '(planes * block.expansion)', 'stride': 'stride'}), '(self._downsample_basic_block, planes=planes * block.expansion,\n    stride=stride)\n', (6446, 6528), False, 'from functools import partial\n'), ((5064, 5094), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.weight', '(1)'], {}), '(m.weight, 1)\n', (5081, 5094), True, 'import torch.nn as nn\n'), ((5111, 5139), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias', '(0)'], {}), '(m.bias, 0)\n', (5128, 5139), True, 'import torch.nn as nn\n'), ((5287, 5313), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (5303, 5313), False, 'import os\n'), ((6762, 6802), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', (['(planes * block.expansion)'], {}), '(planes * block.expansion)\n', (6776, 6802), True, 'import torch.nn as nn\n')]