# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
Testing Invert op in DE
"""
import numpy as np

import mindspore.dataset as ds
import mindspore.dataset.transforms.py_transforms
import mindspore.dataset.vision.py_transforms as F
import mindspore.dataset.vision.c_transforms as C
from mindspore import log as logger
from util import visualize_list, save_and_check_md5, diff_mse

DATA_DIR = "../data/dataset/testImageNetData/train/"

GENERATE_GOLDEN = False


def test_invert_py(plot=False):
    """
    Test Invert python op
    """
    logger.info("Test Invert Python op")

    # Original Images
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)

    transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
                                                                              F.Resize((224, 224)),
                                                                              F.ToTensor()])

    ds_original = data_set.map(operations=transforms_original, input_columns="image")

    ds_original = ds_original.batch(512)

    for idx, (image, _) in enumerate(ds_original):
        if idx == 0:
            images_original = np.transpose(image.asnumpy(), (0, 2, 3, 1))
        else:
            images_original = np.append(images_original,
                                        np.transpose(image.asnumpy(), (0, 2, 3, 1)),
                                        axis=0)

    # Color Inverted Images
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)

    transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
                                                                            F.Resize((224, 224)),
                                                                            F.Invert(),
                                                                            F.ToTensor()])

    ds_invert = data_set.map(operations=transforms_invert, input_columns="image")

    ds_invert = ds_invert.batch(512)

    for idx, (image, _) in enumerate(ds_invert):
        if idx == 0:
            images_invert = np.transpose(image.asnumpy(), (0, 2, 3, 1))
        else:
            images_invert = np.append(images_invert,
                                      np.transpose(image.asnumpy(), (0, 2, 3, 1)),
                                      axis=0)

    num_samples = images_original.shape[0]
    mse = np.zeros(num_samples)
    for i in range(num_samples):
        mse[i] = np.mean((images_invert[i] - images_original[i]) ** 2)
    logger.info("MSE= {}".format(str(np.mean(mse))))

    if plot:
        visualize_list(images_original, images_invert)


def test_invert_c(plot=False):
    """
    Test Invert Cpp op
    """
    logger.info("Test Invert cpp op")

    # Original Images
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)

    transforms_original = [C.Decode(), C.Resize(size=[224, 224])]

    ds_original = data_set.map(operations=transforms_original, input_columns="image")

    ds_original = ds_original.batch(512)

    for idx, (image, _) in enumerate(ds_original):
        if idx == 0:
            images_original = image.asnumpy()
        else:
            images_original = np.append(images_original,
                                        image.asnumpy(),
                                        axis=0)

    # Invert Images
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)

    transform_invert = [C.Decode(), C.Resize(size=[224, 224]),
                        C.Invert()]

    ds_invert = data_set.map(operations=transform_invert, input_columns="image")

    ds_invert = ds_invert.batch(512)

    for idx, (image, _) in enumerate(ds_invert):
        if idx == 0:
            images_invert = image.asnumpy()
        else:
            images_invert = np.append(images_invert,
                                      image.asnumpy(),
                                      axis=0)
    if plot:
        visualize_list(images_original, images_invert)

    num_samples = images_original.shape[0]
    mse = np.zeros(num_samples)
    for i in range(num_samples):
        mse[i] = diff_mse(images_invert[i], images_original[i])
    logger.info("MSE= {}".format(str(np.mean(mse))))


def test_invert_py_c(plot=False):
    """
    Test Invert Cpp op and python op
    """
    logger.info("Test Invert cpp and python op")

    # Invert Images in cpp
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
    data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=["image"])

    ds_c_invert = data_set.map(operations=C.Invert(), input_columns="image")

    ds_c_invert = ds_c_invert.batch(512)

    for idx, (image, _) in enumerate(ds_c_invert):
        if idx == 0:
            images_c_invert = image.asnumpy()
        else:
            images_c_invert = np.append(images_c_invert,
                                        image.asnumpy(),
                                        axis=0)

    # invert images in python
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
    data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224))], input_columns=["image"])

    transforms_p_invert = mindspore.dataset.transforms.py_transforms.Compose([lambda img: img.astype(np.uint8),
                                                                              F.ToPIL(),
                                                                              F.Invert(),
                                                                              np.array])

    ds_p_invert = data_set.map(operations=transforms_p_invert, input_columns="image")

    ds_p_invert = ds_p_invert.batch(512)

    for idx, (image, _) in enumerate(ds_p_invert):
        if idx == 0:
            images_p_invert = image.asnumpy()
        else:
            images_p_invert = np.append(images_p_invert,
                                        image.asnumpy(),
                                        axis=0)

    num_samples = images_c_invert.shape[0]
    mse = np.zeros(num_samples)
    for i in range(num_samples):
        mse[i] = diff_mse(images_p_invert[i], images_c_invert[i])
    logger.info("MSE= {}".format(str(np.mean(mse))))

    if plot:
        visualize_list(images_c_invert, images_p_invert, visualize_mode=2)


def test_invert_one_channel():
    """
     Test Invert cpp op with one channel image
     """
    logger.info("Test Invert C Op With One Channel Images")

    c_op = C.Invert()

    try:
        data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
        data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)),
                                            lambda img: np.array(img[:, :, 0])], input_columns=["image"])

        data_set.map(operations=c_op, input_columns="image")

    except RuntimeError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
        assert "The shape" in str(e)


def test_invert_md5_py():
    """
    Test Invert python op with md5 check
    """
    logger.info("Test Invert python op with md5 check")

    # Generate dataset
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)

    transforms_invert = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
                                                                            F.Invert(),
                                                                            F.ToTensor()])

    data = data_set.map(operations=transforms_invert, input_columns="image")
    # Compare with expected md5 from images
    filename = "invert_01_result_py.npz"
    save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)


def test_invert_md5_c():
    """
    Test Invert cpp op with md5 check
    """
    logger.info("Test Invert cpp op with md5 check")

    # Generate dataset
    data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)

    transforms_invert = [C.Decode(),
                         C.Resize(size=[224, 224]),
                         C.Invert(),
                         F.ToTensor()]

    data = data_set.map(operations=transforms_invert, input_columns="image")
    # Compare with expected md5 from images
    filename = "invert_01_result_c.npz"
    save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)


if __name__ == "__main__":
    test_invert_py(plot=False)
    test_invert_c(plot=False)
    test_invert_py_c(plot=False)
    test_invert_one_channel()
    test_invert_md5_py()
    test_invert_md5_c()

[((1160, 1196), 'mindspore.log.info', 'logger.info', (['"""Test Invert Python op"""'], {}), "('Test Invert Python op')\n", (1171, 1196), True, 'from mindspore import log as logger\n'), ((1235, 1293), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (1256, 1293), True, 'import mindspore.dataset as ds\n'), ((2102, 2160), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (2123, 2160), True, 'import mindspore.dataset as ds\n'), ((3041, 3062), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (3049, 3062), True, 'import numpy as np\n'), ((3365, 3398), 'mindspore.log.info', 'logger.info', (['"""Test Invert cpp op"""'], {}), "('Test Invert cpp op')\n", (3376, 3398), True, 'from mindspore import log as logger\n'), ((3437, 3495), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (3458, 3495), True, 'import mindspore.dataset as ds\n'), ((4023, 4081), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (4044, 4081), True, 'import mindspore.dataset as ds\n'), ((4707, 4728), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (4715, 4728), True, 'import numpy as np\n'), ((4972, 5016), 'mindspore.log.info', 'logger.info', (['"""Test Invert cpp and python op"""'], {}), "('Test Invert cpp and python op')\n", (4983, 5016), True, 'from mindspore import log as logger\n'), ((5060, 5118), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (5081, 5118), True, 'import mindspore.dataset as ds\n'), ((5680, 5738), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (5701, 5738), True, 'import mindspore.dataset as ds\n'), ((6698, 6719), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (6706, 6719), True, 'import numpy as np\n'), ((7062, 7117), 'mindspore.log.info', 'logger.info', (['"""Test Invert C Op With One Channel Images"""'], {}), "('Test Invert C Op With One Channel Images')\n", (7073, 7117), True, 'from mindspore import log as logger\n'), ((7130, 7140), 'mindspore.dataset.vision.c_transforms.Invert', 'C.Invert', ([], {}), '()\n', (7138, 7140), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((7697, 7748), 'mindspore.log.info', 'logger.info', (['"""Test Invert python op with md5 check"""'], {}), "('Test Invert python op with md5 check')\n", (7708, 7748), True, 'from mindspore import log as logger\n'), ((7788, 7846), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (7809, 7846), True, 'import mindspore.dataset as ds\n'), ((8282, 8349), 'util.save_and_check_md5', 'save_and_check_md5', (['data', 'filename'], {'generate_golden': 'GENERATE_GOLDEN'}), '(data, filename, generate_golden=GENERATE_GOLDEN)\n', (8300, 8349), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((8435, 8483), 'mindspore.log.info', 'logger.info', (['"""Test Invert cpp op with md5 check"""'], {}), "('Test Invert cpp op with md5 check')\n", (8446, 8483), True, 'from mindspore import log as logger\n'), ((8523, 8581), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (8544, 8581), True, 'import mindspore.dataset as ds\n'), ((8914, 8981), 'util.save_and_check_md5', 'save_and_check_md5', (['data', 'filename'], {'generate_golden': 'GENERATE_GOLDEN'}), '(data, filename, generate_golden=GENERATE_GOLDEN)\n', (8932, 8981), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((3113, 3166), 'numpy.mean', 'np.mean', (['((images_invert[i] - images_original[i]) ** 2)'], {}), '((images_invert[i] - images_original[i]) ** 2)\n', (3120, 3166), True, 'import numpy as np\n'), ((3242, 3288), 'util.visualize_list', 'visualize_list', (['images_original', 'images_invert'], {}), '(images_original, images_invert)\n', (3256, 3288), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((3524, 3534), 'mindspore.dataset.vision.c_transforms.Decode', 'C.Decode', ([], {}), '()\n', (3532, 3534), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((3536, 3561), 'mindspore.dataset.vision.c_transforms.Resize', 'C.Resize', ([], {'size': '[224, 224]'}), '(size=[224, 224])\n', (3544, 3561), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((4107, 4117), 'mindspore.dataset.vision.c_transforms.Decode', 'C.Decode', ([], {}), '()\n', (4115, 4117), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((4119, 4144), 'mindspore.dataset.vision.c_transforms.Resize', 'C.Resize', ([], {'size': '[224, 224]'}), '(size=[224, 224])\n', (4127, 4144), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((4170, 4180), 'mindspore.dataset.vision.c_transforms.Invert', 'C.Invert', ([], {}), '()\n', (4178, 4180), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((4606, 4652), 'util.visualize_list', 'visualize_list', (['images_original', 'images_invert'], {}), '(images_original, images_invert)\n', (4620, 4652), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((4779, 4825), 'util.diff_mse', 'diff_mse', (['images_invert[i]', 'images_original[i]'], {}), '(images_invert[i], images_original[i])\n', (4787, 4825), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((6770, 6818), 'util.diff_mse', 'diff_mse', (['images_p_invert[i]', 'images_c_invert[i]'], {}), '(images_p_invert[i], images_c_invert[i])\n', (6778, 6818), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((6894, 6960), 'util.visualize_list', 'visualize_list', (['images_c_invert', 'images_p_invert'], {'visualize_mode': '(2)'}), '(images_c_invert, images_p_invert, visualize_mode=2)\n', (6908, 6960), False, 'from util import visualize_list, save_and_check_md5, diff_mse\n'), ((7170, 7228), 'mindspore.dataset.ImageFolderDataset', 'ds.ImageFolderDataset', ([], {'dataset_dir': 'DATA_DIR', 'shuffle': '(False)'}), '(dataset_dir=DATA_DIR, shuffle=False)\n', (7191, 7228), True, 'import mindspore.dataset as ds\n'), ((8608, 8618), 'mindspore.dataset.vision.c_transforms.Decode', 'C.Decode', ([], {}), '()\n', (8616, 8618), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((8645, 8670), 'mindspore.dataset.vision.c_transforms.Resize', 'C.Resize', ([], {'size': '[224, 224]'}), '(size=[224, 224])\n', (8653, 8670), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((8697, 8707), 'mindspore.dataset.vision.c_transforms.Invert', 'C.Invert', ([], {}), '()\n', (8705, 8707), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((8734, 8746), 'mindspore.dataset.vision.py_transforms.ToTensor', 'F.ToTensor', ([], {}), '()\n', (8744, 8746), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((1373, 1383), 'mindspore.dataset.vision.py_transforms.Decode', 'F.Decode', ([], {}), '()\n', (1381, 1383), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((1463, 1483), 'mindspore.dataset.vision.py_transforms.Resize', 'F.Resize', (['(224, 224)'], {}), '((224, 224))\n', (1471, 1483), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((1563, 1575), 'mindspore.dataset.vision.py_transforms.ToTensor', 'F.ToTensor', ([], {}), '()\n', (1573, 1575), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((2238, 2248), 'mindspore.dataset.vision.py_transforms.Decode', 'F.Decode', ([], {}), '()\n', (2246, 2248), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((2326, 2346), 'mindspore.dataset.vision.py_transforms.Resize', 'F.Resize', (['(224, 224)'], {}), '((224, 224))\n', (2334, 2346), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((2424, 2434), 'mindspore.dataset.vision.py_transforms.Invert', 'F.Invert', ([], {}), '()\n', (2432, 2434), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((2512, 2524), 'mindspore.dataset.vision.py_transforms.ToTensor', 'F.ToTensor', ([], {}), '()\n', (2522, 2524), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((5262, 5272), 'mindspore.dataset.vision.c_transforms.Invert', 'C.Invert', ([], {}), '()\n', (5270, 5272), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((6030, 6039), 'mindspore.dataset.vision.py_transforms.ToPIL', 'F.ToPIL', ([], {}), '()\n', (6037, 6039), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((6119, 6129), 'mindspore.dataset.vision.py_transforms.Invert', 'F.Invert', ([], {}), '()\n', (6127, 6129), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((7924, 7934), 'mindspore.dataset.vision.py_transforms.Decode', 'F.Decode', ([], {}), '()\n', (7932, 7934), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((8012, 8022), 'mindspore.dataset.vision.py_transforms.Invert', 'F.Invert', ([], {}), '()\n', (8020, 8022), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((8100, 8112), 'mindspore.dataset.vision.py_transforms.ToTensor', 'F.ToTensor', ([], {}), '()\n', (8110, 8112), True, 'import mindspore.dataset.vision.py_transforms as F\n'), ((3204, 3216), 'numpy.mean', 'np.mean', (['mse'], {}), '(mse)\n', (3211, 3216), True, 'import numpy as np\n'), ((4863, 4875), 'numpy.mean', 'np.mean', (['mse'], {}), '(mse)\n', (4870, 4875), True, 'import numpy as np\n'), ((5159, 5169), 'mindspore.dataset.vision.c_transforms.Decode', 'C.Decode', ([], {}), '()\n', (5167, 5169), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((5171, 5191), 'mindspore.dataset.vision.c_transforms.Resize', 'C.Resize', (['(224, 224)'], {}), '((224, 224))\n', (5179, 5191), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((5779, 5789), 'mindspore.dataset.vision.c_transforms.Decode', 'C.Decode', ([], {}), '()\n', (5787, 5789), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((5791, 5811), 'mindspore.dataset.vision.c_transforms.Resize', 'C.Resize', (['(224, 224)'], {}), '((224, 224))\n', (5799, 5811), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((6856, 6868), 'numpy.mean', 'np.mean', (['mse'], {}), '(mse)\n', (6863, 6868), True, 'import numpy as np\n'), ((7273, 7283), 'mindspore.dataset.vision.c_transforms.Decode', 'C.Decode', ([], {}), '()\n', (7281, 7283), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((7285, 7305), 'mindspore.dataset.vision.c_transforms.Resize', 'C.Resize', (['(224, 224)'], {}), '((224, 224))\n', (7293, 7305), True, 'import mindspore.dataset.vision.c_transforms as C\n'), ((7363, 7387), 'numpy.array', 'np.array', (['img[:, :, (0)]'], {}), '(img[:, :, (0)])\n', (7371, 7387), True, 'import numpy as np\n')]