# Path: common/utils/save_images.py
# def save_images_grid(imgs, path, grid_w=4, grid_h=4, post_processing=postprocessing_tanh, transposed=False):
#     imgs = copy_to_cpu(imgs)
#     if post_processing is not None:
#         imgs = post_processing(imgs)
#     b, ch, w, h = imgs.shape
#     assert b == grid_w*grid_h
# 
#     imgs = imgs.reshape((grid_w, grid_h, ch, w, h))
#     imgs = imgs.transpose(0, 1, 3, 4, 2)
#     if transposed:
#         imgs = imgs.reshape((grid_w, grid_h, w, h, ch)).transpose(1, 2, 0, 3, 4).reshape((grid_h*w, grid_w*h, ch))
#     else:
#         imgs = imgs.reshape((grid_w, grid_h, w, h, ch)).transpose(0, 2, 1, 3, 4).reshape((grid_w*w, grid_h*h, ch))
#     if ch==1:
#         imgs = imgs.reshape((grid_w*w, grid_h*h))
#     cv2.imwrite(path, imgs)


import os
import chainer
import chainer.functions as F
import numpy as np
import os
import cv2
from chainer.training import extension
from chainer import Variable, cuda
from .save_images import save_images_grid

def gan_sampling(gen, eval_folder, gpu, rows=6, cols=6, latent_len=128):
    @chainer.training.make_extension()
    def samples_generation(trainer):
        if not os.path.exists(eval_folder):
            os.makedirs(eval_folder)
        z = np.random.normal(size=(rows*cols, latent_len)).astype("f")
        if gpu>=0:
            z = cuda.to_gpu(z)
        z = Variable(z, volatile=True)
        imgs = gen(z, test=True)

# Path: common/utils/save_images.py
# def save_images_grid(imgs, path, grid_w=4, grid_h=4, post_processing=postprocessing_tanh, transposed=False):
#     imgs = copy_to_cpu(imgs)
#     if post_processing is not None:
#         imgs = post_processing(imgs)
#     b, ch, w, h = imgs.shape
#     assert b == grid_w*grid_h
# 
#     imgs = imgs.reshape((grid_w, grid_h, ch, w, h))
#     imgs = imgs.transpose(0, 1, 3, 4, 2)
#     if transposed:
#         imgs = imgs.reshape((grid_w, grid_h, w, h, ch)).transpose(1, 2, 0, 3, 4).reshape((grid_h*w, grid_w*h, ch))
#     else:
#         imgs = imgs.reshape((grid_w, grid_h, w, h, ch)).transpose(0, 2, 1, 3, 4).reshape((grid_w*w, grid_h*h, ch))
#     if ch==1:
#         imgs = imgs.reshape((grid_w*w, grid_h*h))
#     cv2.imwrite(path, imgs)


# Path: common/utils/evaluation.py
import os
import chainer
import chainer.functions as F
import numpy as np
import os
import cv2
from chainer.training import extension
from chainer import Variable, cuda
from .save_images import save_images_grid


def gan_sampling(gen, eval_folder, gpu, rows=6, cols=6, latent_len=128):
    @chainer.training.make_extension()
    def samples_generation(trainer):
        if not os.path.exists(eval_folder):
            os.makedirs(eval_folder)
        z = np.random.normal(size=(rows*cols, latent_len)).astype("f")
        if gpu>=0:
            z = cuda.to_gpu(z)
        z = Variable(z, volatile=True)
        imgs = gen(z, test=True)

        save_images_grid(imgs, path=eval_folder+"/iter_"+str(trainer.updater.iteration)+".jpg",