import torch


def total_variation(x):
    """Calculates the total variation of neighbouring pixels of an input image

    Usually used as a penalty to reduce noise. A coefficient of around 1e-5 works well.
    """
    width_sum = torch.sum(torch.abs(x[...,1:] - x[..., :-1]))
    height_sum = torch.sum(torch.abs(x[...,1:,:] - x[...,:-1,:]))
    return width_sum + height_sum