"""Expand MNIST with the original image and four one-pixel translations.

Run from src, with ../data/mnist.pkl.gz available. The standard expanded
float32 image array occupies 784,000,000 bytes; serialization needs additional
memory. The output file is created exclusively, so an existing file is preserved.
"""
import gzip
import pickle
from pathlib import Path
import numpy as np


def expand(filename='../data/mnist.pkl.gz', output='../data/mnist_expanded.pkl.gz'):
    with gzip.open(filename, 'rb') as f:
        training, validation, test = pickle.load(f, encoding='latin1')
    images = np.asarray(training[0], dtype=np.float32)
    targets = np.asarray(training[1])
    if images.ndim != 2 or images.shape[1] != 784 or len(images) != len(targets):
        raise ValueError('Expected matched MNIST labels and flattened28by28images')
    count = len(images)
    expanded = np.empty((5*count, 784), dtype=np.float32)
    labels = np.empty(5*count, dtype=targets.dtype)
    positions = np.random.permutation(5*count)
    for i, (pixels, label) in enumerate(zip(images, targets)):
        image = pixels.reshape(28, 28)
        variants = [image]
        for shift, axis in [(1, 0), (-1, 0), (1, 1), (-1, 1)]:
            shifted = np.roll(image, shift, axis=axis)
            if axis == 0:
                shifted[0 if shift == 1 else -1, :] = 0
            else:
                shifted[:, 0 if shift == 1 else -1] = 0
            variants.append(shifted)
        for j, variant in enumerate(variants):
            position = positions[5*i+j]
            expanded[position] = variant.reshape(784)
            labels[position] = label
    with Path(output).open('xb') as raw:
        with gzip.GzipFile(fileobj=raw, mode='wb') as f:
            pickle.dump(((expanded, labels), validation, test), f,
                        protocol=pickle.HIGHEST_PROTOCOL)
    return len(expanded)


if __name__ == '__main__':
    print('Expanded training images:', expand())
