import torch
import torch.nn as nn
import numpy as np
from funcs import *

OPS = {
  'none' : lambda C, stride, affine: Zero(stride),
  'avg_pool_3x3' : lambda C, stride, affine: nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False),
  'max_pool_3x3' : lambda C, stride, affine: nn.MaxPool2d(3, stride=stride, padding=1),
  'skip_connect' : lambda C, stride, affine: Identity() if stride == 1 else FactorizedReduce(C, C, affine=affine),
  'sep_conv_3x3' : lambda C, stride, affine: SepConv(C, C, 3, stride, 1, affine=affine),
  'sep_conv_5x5' : lambda C, stride, affine: SepConv(C, C, 5, stride, 2, affine=affine),
  'sep_conv_7x7' : lambda C, stride, affine: SepConv(C, C, 7, stride, 3, affine=affine),
  'dil_conv_3x3' : lambda C, stride, affine: DilConv(C, C, 3, stride, 2, 2, affine=affine),
  'dil_conv_5x5' : lambda C, stride, affine: DilConv(C, C, 5, stride, 4, 2, affine=affine),
  'conv_7x1_1x7' : lambda C, stride, affine: Conv_7(C, C, stride, affine=affine),
}

class ReLUConvBN(nn.Module):

  def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):
    super(ReLUConvBN, self).__init__()
    self._C_in = C_in
    self._C_out = C_out
    self._kernel_size = kernel_size
    self._stride = stride
    self._padding = padding
    self._affine = affine
    self._groups = C_in
    self.op = self.create_op(C_in, C_out, kernel_size, stride, padding, affine)

  def forward(self, x):
    return self.op(x)

  def create_op(self, C_in, C_out, kernel_size, stride, padding, affine):
      device = torch.device("cuda:%s" % '0' if torch.cuda.is_available() else "cpu")
      op = nn.Sequential(
        nn.ReLU(inplace=False),
        nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=padding, bias=False),
        nn.BatchNorm2d(C_out, affine=affine)
      ).to(device)
      return op

  def update(self, C_in, C_out, grown_channel):
      pass


class DilConv(nn.Module):

  def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine=True):
    super(DilConv, self).__init__()
    self._C_in = C_in
    self._C_out = C_out
    self._kernel_size = kernel_size
    self._stride = stride
    self._padding = padding
    self._dilation = dilation
    self._affine = affine
    self._groups = C_in
    self.op = self.create_op(C_in, C_out, kernel_size, stride, padding, dilation, affine, C_in)

  def forward(self, x):
    return self.op(x)

  def create_op(self, C_in, C_out, kernel_size, stride, padding, dilation, affine, groups):
    op = nn.Sequential(
       nn.ReLU(inplace=False),
       nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=False),
       nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),
       nn.BatchNorm2d(C_out, affine=affine),
       )
    return op

  def update(self, groups = None):
    if groups == None:
      if self._groups != 1:
        self._groups = self._groups // 2
        if self._groups == 0:
            self._groups = 1
        self.op = self.create_op(self._C_in, self._C_out, self._kernel_size, self._stride, self._padding, self._dilation, self._affine, groups = self._groups)#.cuda()
    else:
      self._groups = groups
      self.op = self.create_op(self._C_in, self._C_out, self._kernel_size, self._stride, self._padding, self._dilation, self._affine, groups = self._groups)#.cuda()

    return self._groups



class SepConv(nn.Module):

  def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):
    super(SepConv, self).__init__()
    self._C_in = C_in
    self._C_out = C_out
    self._kernel_size = kernel_size
    self._stride = stride
    self._padding = padding
    self._affine = affine
    self._groups = C_in
    self.op = self.create_op(C_in, C_out, kernel_size, stride, padding, affine, C_in)

  def forward(self, x):
    return self.op(x)

  def create_op(self, C_in, C_out, kernel_size, stride, padding, affine, groups):
      op = nn.Sequential(
        nn.ReLU(inplace=False),
        nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False),
        nn.Conv2d(C_in, C_in, kernel_size=1, padding=0, bias=False),
        nn.BatchNorm2d(C_in, affine=affine),
        nn.ReLU(inplace=False),
        nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=1, padding=padding, groups=groups, bias=False),
        nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),
        nn.BatchNorm2d(C_out, affine=affine),
        )
      return op

  def update(self, groups = None):
    if groups == None:
      if self._groups != 1:
        self._groups = self._groups // 2
        if self._groups == 0:
            self._groups = 1
        self.op = self.create_op(self._C_in, self._C_out, self._kernel_size, self._stride, self._padding, self._affine, groups = self._groups)#.cuda()
    else:
      self._groups = groups
      self.op = self.create_op(self._C_in, self._C_out, self._kernel_size, self._stride, self._padding, self._affine, groups = self._groups)#.cuda()

    return self._groups


class Identity(nn.Module):

  def __init__(self):
    super(Identity, self).__init__()
    self._groups = 0

  def forward(self, x):
    return x
  def update(self):
    pass


class Zero(nn.Module):

  def __init__(self, stride):
    super(Zero, self).__init__()
    self.stride = stride
    self._groups = 0

  def forward(self, x):
    if self.stride == 1:
      return x.mul(0.)
    return x[:,:,::self.stride,::self.stride].mul(0.)
  def update(self, C_in, C_out, grown_channel):
    pass

class FactorizedReduce(nn.Module):

  def __init__(self, C_in, C_out, affine=True):
    super(FactorizedReduce, self).__init__()
    self._C_in = C_in
    self._C_out = C_out
    self._groups = C_in
    self._affine = affine
    self.create_op(C_in, C_out, affine)

  def create_op(self, C_in, C_out, affine):
      device = torch.device("cuda:%s" % '0' if torch.cuda.is_available() else "cpu")
      assert C_out % 2 == 0
      self._C_in = C_in
      self._C_out = C_out
      self.relu = nn.ReLU(inplace=False).to(device)
      self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False).to(device)
      self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False).to(device)
      self.bn = nn.BatchNorm2d(C_out, affine=affine).to(device)

  def forward(self, x):
    x = self.relu(x)
    out = torch.cat([self.conv_1(x), self.conv_2(x[:,:,1:,1:])], dim=1)
    out = self.bn(out)
    return out

  def update(self):
    pass

class Conv_7(nn.Module):

  def __init__(self, C_in, C_out, stride, affine=True):
    super(Conv_7, self).__init__()
    self._C_in = C_in
    self._C_out = C_out
    self._stride = stride
    self._affine = affine
    self._groups = C_in
    self.op = self.create_op(C_in, C_out, kernel_size, stride, padding, affine)

  def forward(self, x):
    return self.op(x)

  def create_op(self, C_in, C_out, stride, affine):
      op = nn.Sequential(
        nn.ReLU(inplace=False),
        nn.Conv2d(C_in, C_in, (1,7), stride=(1, stride), padding=(0, 3), bias=False),
        nn.Conv2d(C_in, C_in, (7,1), stride=(stride, 1), padding=(3, 0), bias=False),
        nn.BatchNorm2d(C_out, affine=affine)
      )
      return op

  def update(self):
    pass
