import base64
import math
import re
from io import BytesIO

import matplotlib.cm
import numpy as np
import torch
import torch.nn
from PIL import Image

# Compute edge magnitudes
from scipy import ndimage


class RunningAverage:
    def __init__(self):
        self.avg = 0
        self.count = 0

    def append(self, value):
        self.avg = (value + self.count * self.avg) / (self.count + 1)
        self.count += 1

    def get_value(self):
        return self.avg


def denormalize(x, device='cpu'):
    mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device)
    std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device)
    return x * std + mean


class RunningAverageDict:
    def __init__(self):
        self._dict = None

    def update(self, new_dict):
        if self._dict is None:
            self._dict = dict()
            for key, _ in new_dict.items():
                self._dict[key] = RunningAverage()

        for key, value in new_dict.items():
            self._dict[key].append(value)

    def get_value(self):
        return {key: value.get_value() for key, value in self._dict.items()}


def colorize(value, vmin=10, vmax=1000, cmap='magma_r'):
    value = value.cpu().numpy()[0, :, :]
    invalid_mask = value == -1

    # normalize
    vmin = value.min() if vmin is None else vmin
    vmax = value.max() if vmax is None else vmax
    if vmin != vmax:
        value = (value - vmin) / (vmax - vmin)  # vmin..vmax
    else:
        # Avoid 0-division
        value = value * 0.0
    # squeeze last dim if it exists
    # value = value.squeeze(axis=0)
    cmapper = matplotlib.cm.get_cmap(cmap)
    value = cmapper(value, bytes=True)  # (nxmx4)
    value[invalid_mask] = 255
    img = value[:, :, :3]

    #     return img.transpose((2, 0, 1))
    return img


def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


def compute_errors(gt, pred):
    thresh = np.maximum((gt / pred), (pred / gt))
    a1 = (thresh < 1.25).mean()
    a2 = (thresh < 1.25 ** 2).mean()
    a3 = (thresh < 1.25 ** 3).mean()

    abs_rel = np.mean(np.abs(gt - pred) / gt)
    sq_rel = np.mean(((gt - pred) ** 2) / gt)

    rmse = (gt - pred) ** 2
    rmse = np.sqrt(rmse.mean())

    rmse_log = (np.log(gt) - np.log(pred)) ** 2
    rmse_log = np.sqrt(rmse_log.mean())

    err = np.log(pred) - np.log(gt)
    silog = np.sqrt(np.mean(err ** 2) - np.mean(err) ** 2) * 100

    log_10 = (np.abs(np.log10(gt) - np.log10(pred))).mean()
    return dict(
        a1=a1,
        a2=a2,
        a3=a3,
        abs_rel=abs_rel,
        rmse=rmse,
        log_10=log_10,
        rmse_log=rmse_log,
        silog=silog,
        sq_rel=sq_rel,
    )


# Demo Utilities
def b64_to_pil(b64string):
    image_data = re.sub('^data:image/.+;base64,', '', b64string)
    # image = Image.open(cStringIO.StringIO(image_data))
    return Image.open(BytesIO(base64.b64decode(image_data)))


def edges(d):
    dx = ndimage.sobel(d, 0)  # horizontal derivative
    dy = ndimage.sobel(d, 1)  # vertical derivative
    return np.abs(dx) + np.abs(dy)


class PointCloudHelper:
    def __init__(self, width=640, height=480):
        self.xx, self.yy = self.worldCoords(width, height)

    def worldCoords(self, width=640, height=480):
        hfov_degrees, vfov_degrees = 57, 43
        hFov = math.radians(hfov_degrees)
        vFov = math.radians(vfov_degrees)
        cx, cy = width / 2, height / 2
        fx = width / (2 * math.tan(hFov / 2))
        fy = height / (2 * math.tan(vFov / 2))
        xx, yy = np.tile(range(width), height), np.repeat(range(height), width)
        xx = (xx - cx) / fx
        yy = (yy - cy) / fy
        return xx, yy

    def depth_to_points(self, depth):
        depth[edges(depth) > 0.3] = np.nan  # Hide depth edges
        length = depth.shape[0] * depth.shape[1]
        # depth[edges(depth) > 0.3] = 1e6  # Hide depth edges
        z = depth.reshape(length)

        return np.dstack((self.xx * z, self.yy * z, z)).reshape((length, 3))

[((2040, 2072), 'numpy.maximum', 'np.maximum', (['(gt / pred)', '(pred / gt)'], {}), '(gt / pred, pred / gt)\n', (2050, 2072), True, 'import numpy as np\n'), ((2249, 2279), 'numpy.mean', 'np.mean', (['((gt - pred) ** 2 / gt)'], {}), '((gt - pred) ** 2 / gt)\n', (2256, 2279), True, 'import numpy as np\n'), ((2891, 2938), 're.sub', 're.sub', (['"""^data:image/.+;base64,"""', '""""""', 'b64string'], {}), "('^data:image/.+;base64,', '', b64string)\n", (2897, 2938), False, 'import re\n'), ((3088, 3107), 'scipy.ndimage.sobel', 'ndimage.sobel', (['d', '(0)'], {}), '(d, 0)\n', (3101, 3107), False, 'from scipy import ndimage\n'), ((3143, 3162), 'scipy.ndimage.sobel', 'ndimage.sobel', (['d', '(1)'], {}), '(d, 1)\n', (3156, 3162), False, 'from scipy import ndimage\n'), ((2451, 2463), 'numpy.log', 'np.log', (['pred'], {}), '(pred)\n', (2457, 2463), True, 'import numpy as np\n'), ((2466, 2476), 'numpy.log', 'np.log', (['gt'], {}), '(gt)\n', (2472, 2476), True, 'import numpy as np\n'), ((3198, 3208), 'numpy.abs', 'np.abs', (['dx'], {}), '(dx)\n', (3204, 3208), True, 'import numpy as np\n'), ((3211, 3221), 'numpy.abs', 'np.abs', (['dy'], {}), '(dy)\n', (3217, 3221), True, 'import numpy as np\n'), ((3473, 3499), 'math.radians', 'math.radians', (['hfov_degrees'], {}), '(hfov_degrees)\n', (3485, 3499), False, 'import math\n'), ((3516, 3542), 'math.radians', 'math.radians', (['vfov_degrees'], {}), '(vfov_degrees)\n', (3528, 3542), False, 'import math\n'), ((2211, 2228), 'numpy.abs', 'np.abs', (['(gt - pred)'], {}), '(gt - pred)\n', (2217, 2228), True, 'import numpy as np\n'), ((2365, 2375), 'numpy.log', 'np.log', (['gt'], {}), '(gt)\n', (2371, 2375), True, 'import numpy as np\n'), ((2378, 2390), 'numpy.log', 'np.log', (['pred'], {}), '(pred)\n', (2384, 2390), True, 'import numpy as np\n'), ((3028, 3056), 'base64.b64decode', 'base64.b64decode', (['image_data'], {}), '(image_data)\n', (3044, 3056), False, 'import base64\n'), ((2498, 2515), 'numpy.mean', 'np.mean', (['(err ** 2)'], {}), '(err ** 2)\n', (2505, 2515), True, 'import numpy as np\n'), ((3610, 3628), 'math.tan', 'math.tan', (['(hFov / 2)'], {}), '(hFov / 2)\n', (3618, 3628), False, 'import math\n'), ((3658, 3676), 'math.tan', 'math.tan', (['(vFov / 2)'], {}), '(vFov / 2)\n', (3666, 3676), False, 'import math\n'), ((4111, 4151), 'numpy.dstack', 'np.dstack', (['(self.xx * z, self.yy * z, z)'], {}), '((self.xx * z, self.yy * z, z))\n', (4120, 4151), True, 'import numpy as np\n'), ((546, 581), 'torch.Tensor', 'torch.Tensor', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (558, 581), False, 'import torch\n'), ((621, 656), 'torch.Tensor', 'torch.Tensor', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\n', (633, 656), False, 'import torch\n'), ((2518, 2530), 'numpy.mean', 'np.mean', (['err'], {}), '(err)\n', (2525, 2530), True, 'import numpy as np\n'), ((2567, 2579), 'numpy.log10', 'np.log10', (['gt'], {}), '(gt)\n', (2575, 2579), True, 'import numpy as np\n'), ((2582, 2596), 'numpy.log10', 'np.log10', (['pred'], {}), '(pred)\n', (2590, 2596), True, 'import numpy as np\n')]