# -*- coding: utf-8 -*-
"""Paper4_DENSE_UNET.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1pMylVX1NkSDSmMMoHUrVXlH9oEftvMTh

# colab + unzip
"""

from google.colab import drive
drive.mount('/content/drive')

# # unzip in colab
# !unzip /content/drive/MyDrive/Bản\ sao\ của\ Linemod_preprocessed.zip -d /content

!unzip "/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/GENERAL DATA/Linemod_preprocessed.zip" -d /content

"""# load path"""

import os
import numpy as np

directory_path = "/content/Linemod_preprocessed/data" # đường dẫn ổ đĩa drive colab
# directory_path = "../data/Linemod_preprocessed/data" # đường dẫn ổ đĩa PC
folder_dir = []

if os.path.exists(directory_path) and os.path.isdir(directory_path):
  for item in os.listdir(directory_path):
    item_path = os.path.join(directory_path, item)
    if os.path.isdir(item_path):
      folder_dir.append(item_path)
else:
  print(f"The directory '{directory_path}' does not exist or is not a directory.")

folder_dir.sort()
folder_test = [folder_dir[1]]
folder_train = [folder_dir[0]] + folder_dir[2:]
print('All Folder: ', folder_dir)
print('Folder test: ', folder_test)
print('Folder train', folder_train)
print()

# # Lấy tên file
# rgb_dir_train = []
# depth_dir_train = []
# rgb_dir_test = []
# depth_dir_test = []

"""# load path train & validation"""

def get_path_folder(folder_dir):
    rgb_dir = []
    depth_dir = []

    for item in folder_dir:
        path_rgb = os.path.join(item, 'rgb')
        path_depth = os.path.join(item, 'depth')

        lt1 = os.listdir(path_rgb)
        lt2 = os.listdir(path_depth)

        lt1.sort()
        lt2.sort()

        if len(lt1) == len(lt2):
            print(len(lt1), path_rgb, lt1)
            print(len(lt2), path_depth, lt2)

            print()

            # Tạo danh sách đường dẫn các ảnh rgb và ảnh depth
            for i in range(len(lt1)):
                rgb_dir.append(os.path.join(path_rgb, lt1[i]))
                depth_dir.append(os.path.join(path_depth, lt2[i]))

    # nối 2 danh sáh đường dẫn
    return np.column_stack((np.array(rgb_dir), np.array(depth_dir)))

matrix_train = get_path_folder(folder_train)
matrix_train.shape

"""# load path test"""

rgb_dir = []
depth_dir = []
mask_dir = []

for item in folder_test:
    path_rgb = os.path.join(item, 'rgb')
    path_depth = os.path.join(item, 'depth')
    path_mask = os.path.join(item, 'mask_all')

    lt1 = os.listdir(path_rgb)
    lt2 = os.listdir(path_depth)
    lt3 = os.listdir(path_mask)

    lt1.sort()
    lt2.sort()
    lt3.sort()

    if len(lt1) == len(lt2):
        print(path_rgb, len(lt1), lt1)
        print(path_depth, len(lt2), lt2)
        print(path_mask, len(lt3), lt3)

        print()

        # Tạo danh sách đường dẫn các ảnh rgb và ảnh depth
        for i in range(len(lt1)):
            rgb_dir.append(os.path.join(path_rgb, lt1[i]))
            depth_dir.append(os.path.join(path_depth, lt2[i]))
            mask_dir.append(os.path.join(path_mask, lt3[i]))

matrix_test = np.column_stack((np.array(rgb_dir), np.array(depth_dir), np.array(mask_dir)))
matrix_test.shape

"""# visual originnal image"""

import matplotlib.pyplot as plt
import cv2
import seaborn as sns

# Giả sử matrix là ma trận chứa đường dẫn đến các ảnh
for i in range(0, matrix_train.shape[0], matrix_train.shape[0] // 3):
    plt.figure(figsize=(12, 5))
    plt.suptitle(f'Ảnh thứ {i}: {matrix_train[i, 0]}', fontsize=16)

    # Hiển thị ảnh thứ nhất với colorbar
    plt.subplot(1, 2, 1)
    img1 = cv2.imread(matrix_train[i, 0], 1)
    im1 = plt.imshow(img1)
    plt.colorbar(im1)
    plt.axis('off')

    # Hiển thị ảnh thứ hai với colorbar
    plt.subplot(1, 2, 2)
    img2 = cv2.imread(matrix_train[i, 1], -1)
    im2 = plt.imshow(img2)
    plt.colorbar(im2)
    plt.axis('off')

    plt.tight_layout()
    plt.show()

"""# choice size"""

x, y = img2.shape
width, height = int(x * 0.4), int(y * 0.4)
width, height

"""# load X & y | X_test & y_test"""

X = []
y = []

import cv2
import numpy as np
import matplotlib.pyplot as plt

for i in range(0, matrix_train.shape[0]):

    if i % 600 == 0:
      print(i, end=' ')

    # if i <= 4800:
    #   continue
    if i >= 4800:
      break

    rgb_path = matrix_train[i, 0]
    depth_path = matrix_train[i, 1]

    # Read images using cv2
    img_rgb = cv2.imread(rgb_path)
    img_depth = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED) # Keep depth as is

    if img_rgb is not None and img_depth is not None:
      img_rgb = cv2.resize(img_rgb, (height, width), interpolation=cv2.INTER_AREA)
      img_depth = cv2.resize(img_depth, (height, width), interpolation=cv2.INTER_AREA)

      X.append(img_rgb)
      y.append(img_depth)

    else:
      print(f"Error loading images at index {i}")

X = np.array(X)
y = np.array(y)

print()

X_test = []
y_test = []

import cv2
import numpy as np
import matplotlib.pyplot as plt

for i in range(0, matrix_test.shape[0]):
    rgb_path = matrix_test[i, 0]
    depth_path = matrix_test[i, 1]

    if i % 200 == 0:
      print(i, end=' ')

    # Read images using cv2
    img_rgb = cv2.imread(rgb_path)
    # Khong thay doi gia tri anh depth .png
    img_depth = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED) # Keep depth as is

    if img_rgb is not None and img_depth is not None:
      img_rgb = cv2.resize(img_rgb, (height, width), interpolation=cv2.INTER_AREA)
      img_depth = cv2.resize(img_depth, (height, width), interpolation=cv2.INTER_AREA)

      X_test.append(img_rgb)
      y_test.append(img_depth)

    else:
      print(f"Error loading images at index {i}")

X_test = np.array(X_test)
y_test = np.array(y_test)

print()
print(X.shape, y.shape)
print(X_test.shape, y_test.shape)

"""# Scale values dataset"""

resized_X = []
kernel_size = (3, 3)

for image in X:
  dst = cv2.GaussianBlur(image, kernel_size, 0)
  resized_X.append(dst)

X = (np.array(resized_X) / 255.0).astype(np.float32)
resized_X = None

resized_X = []
for image in X_test:
  dst = cv2.GaussianBlur(image, kernel_size, 0)
  resized_X.append(dst)

X_test = (np.array(resized_X) / 255.0).astype(np.float32)
# Xóa bộ nhớ
resized_X = None

max_depth_y = np.max(y)
max_depth_y_test = np.max(y_test)
print(max_depth_y, max_depth_y_test)

y = (y / max_depth_y).astype(np.float32)
y_test = (y_test / max_depth_y_test).astype(np.float32)

max_depth_y_process = np.max(y)
max_depth_y_test_process = np.max(y_test)
print(max_depth_y_process, max_depth_y_test_process)

"""# process label"""

import cv2
import numpy as np

def blur_median_label(y:np.array):
    y_median = []
    for i in range(y.shape[0]):
        img = y[i]
        # Nếu có thêm chiều kênh cuối (ví dụ (N, H, W, 1)), loại bỏ chiều này
        if img.ndim == 3 and img.shape[-1] == 1:
            img = np.squeeze(img, axis=-1)
        # Chuyển về uint8 để medianBlur hoạt động
        img_med = cv2.medianBlur(img, 3)
        y_median.append(img_med)
    return np.array(y_median)

y = blur_median_label(y).astype(np.float32)
y_test = blur_median_label(y_test).astype(np.float32)

y = np.expand_dims(np.squeeze(y), -1)
y_test = np.expand_dims(np.squeeze(y_test), -1)

"""# visual train image"""

import matplotlib.pyplot as plt
import cv2
import seaborn as sns

# Giả sử matrix là ma trận chứa đường dẫn đến các ảnh
for i in range(0, X.shape[0], (X.shape[0] // 2) -1 ):
    plt.figure(figsize=(8,6))

    # Hiển thị ảnh thứ nhất với colorbar
    img1 = X[i]
    plt.title(f"RGB Origin")
    im1 = plt.imshow(img1)
    plt.colorbar(im1)
    plt.tight_layout()
    plt.show()

    plt.figure(figsize=(8, 6))
    # Hiển thị ảnh thứ hai với colorbar
    img2 = y[i]
    plt.title(f"Label")
    im2 = plt.imshow(img2)
    plt.colorbar(im2)

    plt.tight_layout()
    plt.show()

"""# Visualization image test"""

import matplotlib.pyplot as plt
import cv2
import seaborn as sns

# Giả sử matrix là ma trận chứa đường dẫn đến các ảnh
for i in range(0, X_test.shape[0],  (X_test.shape[0] // 2) - 1):

    plt.figure(figsize=(8, 6))
    # Hiển thị ảnh thứ nhất với colorbar
    img1 = X_test[i]
    plt.title(f'GT')
    im1 = plt.imshow(img1)
    plt.colorbar(im1)
    plt.tight_layout()
    plt.show()

    plt.figure(figsize=(8, 6))
    # Hiển thị ảnh thứ hai với colorbar
    img2 = y_test[i]
    plt.title(f'Label')
    im2 = plt.imshow(img2)
    plt.colorbar(im2)

    plt.tight_layout()
    plt.show()

"""# Split data"""

import numpy as np
from sklearn.model_selection import train_test_split

# y = np.expand_dims(np.squeeze(y), -1)
# y_test = np.expand_dims(np.squeeze(y_test), -1)

print(np.array(X).shape, y.shape)
print()

# Split data into train, test, and validation sets
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, random_state=42)

print(f"Train set size: { X_train.shape}, {y_train.shape}")
print("Validation set size:", {X_val.shape}, {y_val.shape})
print("Test set size:", {X_test.shape}, {y_test.shape})

X, y = None, None
X_train.shape, y_train.shape, X_test.shape, y_test.shape, X_val.shape, y_val.shape

"""# PAPER 1: [Unsupervised Monocular Depth Learning in Dynamic Scenes. In CVF 2019](https://github.com/google-research/google-research/tree/master/depth_and_motion_learning)"""

from tensorflow.keras.layers import Input, concatenate, LeakyReLU, BatchNormalization, Conv2D, MaxPooling2D, Dropout, UpSampling2D
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from skimage.transform import resize
import os
import csv
import PIL
import numpy as np
import random
import cv2
import imutils
import tensorflow.keras.backend as K
import tensorflow as tf

"""# PAPER 2: [StaSiS-Net: a stacked and siamese stereo network for depth reconstruction in modern 3D laparoscopy. In Medical Image Analysis Volume 77, April 2022, 102380 ](https://github.com/lodeguns/StaSiS-Net)

"
If you use this code, you must cite this paper:

Bardozzo, Francesco, et al. "StaSiS-Net: A stacked and siamese disparity estimation network for depth reconstruction
in modern 3D laparoscopy." Medical Image Analysis 77 (2022): 102380.

Bardozzo, Francesco, et al. "Cross X-AI: Explainable Semantic Segmentation of Laparoscopic Images in Relation
to Depth Estimation." 2022 International Joint Conference on Neural Networks (IJCNN). IEEE, 2022.

Download the files here: https://drive.google.com/drive/folders/1_atwJnYU61aGYjrKrhh8s32mgfpzYdhh?usp=sharing

> python3 run_stasis.py

Thank you!

## hamy_network
"""

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, Concatenate, LeakyReLU, BatchNormalization, MaxPool2D, ReLU, Activation, MaxPooling2D, AveragePooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D, Add, concatenate, Dropout
from tensorflow.keras.initializers import RandomNormal, HeNormal, VarianceScaling, HeUniform, GlorotUniform, GlorotNormal

def hamy_network(input_shape, k1=32):
    input = Input(shape=input_shape)
    #conv1
    encoded  = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(input)
    encoded  = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)
    #conv2
    encoded  = Conv2D(k1*2, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*2, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)
    #conv3
    encoded  = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)
    #conv4
    encoded  = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)

    #conv5
    encoded  = Conv2D(k1*16, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*16, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = Conv2D(k1*16, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)

    decoded = Conv2D(k1*32, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(k1*16, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*16, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*16, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(k1*2, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1*2, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded  = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    return Model(input, decoded)

model = hamy_network((192, 256, 3), k1=20)
model.summary()

"""## res_network"""

import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.models import Model

def create_res_network(input_shape, k1=32):
    '''Base/ResNet101 network'''
    input = Input(shape=input_shape)
    x = tf.keras.applications.resnet.preprocess_input(input)
    core =  tf.keras.applications.ResNet50(include_top=False, weights=None, pooling=None)
    x = core(x)

    encoded = Conv2D(1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(x)
    encoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    mod = Model(input, decoded)
    return mod

model = create_res_network((192, 256, 3), k1=12)
model.summary()

"""## create_base_network_v3"""

def create_base_network_v3(input_shape, k1=32):
    '''Base network to be shared (eq. to feature extraction).
    '''
    input = Input(shape=input_shape)

    #enc1
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(input)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded_2 = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_2)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded_3 = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_3)

    encoded = Conv2D(k1*2, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    encoded = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)
    decoded = Conv2D(k1*8, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(encoded)  # <- questa potrebbe essere relu+
    decoded = Conv2D(k1*4, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1*2, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)


    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_3])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_2])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    decoded = Conv2D(1, (1, 1), activation='sigmoid', padding='same', kernel_regularizer = tf.keras.regularizers.L2(0.0001), activity_regularizer=tf.keras.regularizers.L2(0.0001), bias_regularizer=tf.keras.regularizers.L2(0.0001))(decoded)

    return Model(input, decoded)

model = create_base_network_v3((192, 256, 3), k1=128)
model.summary()

'''
If you use this code you must cite these papers:
Bardozzo, Francesco, et al. "StaSiS-Net: A stacked and siamese disparity estimation network for depth reconstruction
in modern 3D laparoscopy." Medical Image Analysis 77 (2022): 102380.

Bardozzo, Francesco, et al. "Cross X-AI: Explainable Semantic Segmentation of Laparoscopic Images in Relation
to Depth Estimation." 2022 International Joint Conference on Neural Networks (IJCNN). IEEE, 2022.
'''


from __future__ import absolute_import
from __future__ import print_function
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
from os import path

from tensorflow.python.keras.layers import Conv3D, UpSampling3D, MaxPooling3D

config = ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)
import os
from os import path
import argparse
import tensorflow as tf
#import tensorflow_addons as tfa

from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, Flatten, Dense, Activation, Concatenate, Dot
from tensorflow.keras.callbacks import TensorBoard, LearningRateScheduler
import math
from datetime import datetime
import pathlib


# print("Francesco Bardozzo - 25 Agosto 2020 ")
# parser = argparse.ArgumentParser(description='Stereo depth enstimation')
# parser.add_argument('--train_setting_flow',        type=int,   help='0 = LtoR (Basic), 1 = RtoL (Basic), 2=LRtoR (Twin), 3=RLtoL (Twin)', default=0)
# parser.add_argument('--simple_model',              type=int,   help='0 = base_network_model, 1 = simple network model', default=0)
# parser.add_argument('--shared_model',              type=int,   help='(Twin) Shared_model = 0, False=1, Transfer Single Branches Learning = 2', default=0)
# parser.add_argument('--exp_name',                  type=str,   help='name of the experiment', default="Experiment0Marconi100")
# parser.add_argument('--input_height',              type=int,   help='input height', default=192)
# parser.add_argument('--input_width',               type=int,   help='input width', default=384)
# parser.add_argument('--batch_size',                type=int,   help='batch size', default=30)
# parser.add_argument('--num_epochs',                type=int,   help='number of epochs', default=100)
# parser.add_argument('--lr',                        type=float, help='initial learning rate', default=0.01)
# parser.add_argument('--train_size_set',            type=int,   help='train_size_set', default=34240)
# parser.add_argument('--test_size_set',             type=int,   help='test_size_set', default=7191)
# parser.add_argument('--k1',                        type=int,   help='k_base def 32', default=32)
# parser.add_argument('--d1',                        type=int,   help='dense neurons base 300', default=300)
# parser.add_argument('--alpha1',                    type=float, help='alpha1', default=0.2)
# parser.add_argument('--alpha2',                    type=float, help='alpha2', default=0.7)
# parser.add_argument('--alpha3',                    type=float, help='alpha3', default=0.1)
# parser.add_argument('--learning_rate_decay',       type=int,   help='LR decay yes (1), no(0)', default=0)
# parser.add_argument('--learning_rate_plateau',     type=int,   help='LR reduce LR plateau monitoring loss yes (1), no(0)', default=0)
# parser.add_argument('--decay_factor_lr',           type=float, help='decay learning rate', default=0.9)
# parser.add_argument('--patience_decay',            type=int,   help='patience decay learning rate', default=5)
# parser.add_argument('--selected_imgs',             type=int,   help='Img depths (1) or the whole dataset (0)', default=0)
# parser.add_argument('--continue_fit',              type=str,   help="Continue training no(0), yes the name of the checkpoint ex 030", default='0')
# parser.add_argument('--gpus',                      type=int,   default=1, help='The number of GPUs to use')
# parser.add_argument('--gpuids',                    type=str,   default='0', help='IDs of GPUs to use 0,1,2,3,4,5,6,7')

# args = parser.parse_args()

# # Inform about multi-gpu training
# if args.gpus == 1:
#     os.environ['CUDA_VISIBLE_DEVICES'] = args.gpuids
#     print('-------  Will use GPU ' + args.gpuids) #usage 0,1,2,3,4,5,6,7
# else:
#     print('-------- Will use ' + str(args.gpus) + ' GPUs.')
# # Create a MirroredStrategy.
# strategy = tf.distribute.MirroredStrategy()
# print('--- Number of devices: {}'.format(strategy.num_replicas_in_sync))



# EPOCHS     = args.num_epochs
# BATCH_SIZE = args.batch_size
# IMG_HEIGHT = args.input_height
# IMG_WIDTH  = args.input_width
# LEARNING_RATE = args.lr
# LEFT_RIGHT_TRAIN = args.train_size_set
# LEFT_RIGHT_TEST  = args.test_size_set
# margin  =  1 #contrastive loss
# alpha1  =  args.alpha1
# alpha2  =  args.alpha2
# alpha3  =  args.alpha3
# decay_factor = args.decay_factor_lr
# patience_lr  = args.patience_decay
# k1  = args.k1
# d1  = args.k1
# shared_model = args.shared_model
# train_setting_flow = args.train_setting_flow
# learning_rate_decay = args.learning_rate_decay
# learning_rate_plateau = args.learning_rate_plateau
# selected_imgs = args.selected_imgs
# continue_fit  = args.continue_fit
# simple_model = args.simple_model

def all_subdirs_of(b='.'):
  result = []
  for d in os.listdir(b):
    bd = os.path.join(b, d)
    if os.path.isdir(bd): result.append(bd)
  return result


def tensor_checkpoints_and_retrain(note, continue_fit = 0):
    if continue_fit != '0':
        all_subdirs = all_subdirs_of('checkpoints')
        latest_subdir = max(all_subdirs, key=os.path.getmtime).split('/')
        name_folder = latest_subdir[1] + "_continue_fit"
    else:
        name_folder = str(datetime.now().strftime("D%Y%m%d%H%M%S")) + "E" \
                      + str(EPOCHS) + "BS" + str(BATCH_SIZE) + "LR" + str(LEARNING_RATE).replace('.', '') + note

    os.makedirs('tensorboard/' + str(name_folder), exist_ok=True)
    os.makedirs('saved_models/' + str(name_folder), exist_ok=True)
    os.makedirs('checkpoints/' + str(name_folder), exist_ok=True)

    # TENSORBOARD
    # tensorboard --logdir=/tmp/depth_trace

    log_dir = 'tensorboard/' + name_folder + '/'
    tb_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)

    # CHECKPOINT
    checkpoint_path = "checkpoints/" + str(name_folder) + "/{epoch:03d}.hdf5"
    checkpoint_dir = path.dirname(checkpoint_path)
    model_path = "saved_models/" + str(name_folder)

    cp_callback = tf.keras.callbacks.ModelCheckpoint(
        filepath=checkpoint_path,
        monitor='ssi_acc',
        verbose=1,
        save_best_only=False,
        mode='max',
        save_freq='epoch')



    return name_folder, log_dir, tb_callback, checkpoint_path, checkpoint_dir, cp_callback, model_path


def load_LR_net(path_hdf5):
    print("Loading LR network model")
    LR_mod = tf.keras.models.load_model(path_hdf5,
                                        custom_objects={'ssi_loss': ssi_loss,
                                                        'ssi_acc': ssi_acc,
                                                        'cc_acc': cc_acc,
                                                        'loss_final': loss_final,
                                                        'acc_final': acc_final})

    LR_mod = Model(LR_mod.input, LR_mod.layers[-1].output)
    print(LR_mod.summary())

    return LR_mod


def load_RL_net(path_hdf5):
    print("Loading RL network model")
    RL_mod = tf.keras.models.load_model(path_hdf5,
                                        custom_objects={'ssi_loss': ssi_loss,
                                                        'ssi_acc': ssi_acc,
                                                        'cc_acc': cc_acc,
                                                        'loss_final': loss_final,
                                                        'acc_final': acc_final})

    RL_mod = Model(RL_mod.input, RL_mod.layers[-1].output)
    print(RL_mod.summary())
    return RL_mod


def load_model_from_checkpoint(path_hdf5):
    #example path hdf5 './checkpoints/D20200525221639E50BS60LR0001Skip-Sub2/046.hdf5'
    siamese = tf.keras.models.load_model(path_hdf5,
                                         custom_objects={'ssi_loss': ssi_loss,
                                                         'ssi_acc': ssi_acc,
                                                         'cc_acc': cc_acc,
                                                         'loss_final':loss_final,
                                                         'acc_final':acc_final})
    return siamese



def load_path_dataset(selected_imgs):
    if selected_imgs == 0:
        ''' Train set Left / Right'''
        L1 = pathlib.Path('data/train_set/L')
        R1 = pathlib.Path('data/train_set/R')

        ''' Test set Left / Right'''
        L2 = pathlib.Path('data/test_set/L')
        R2 = pathlib.Path('data/test_set/R')
    else:
        ''' Train set Depth enst Left / Right'''
        L1 = pathlib.Path('data_depth/train_set_depth/L')
        R1 = pathlib.Path('data_depth/train_set_depth/R')

        ''' Test set Depth enst  Left / Right'''
        L2 = pathlib.Path('data_depth/test_set_depth/L')
        R2 = pathlib.Path('data_depth/test_set_depth/R')
    return L1, R1, L2, R2




# # The 1./255 is to convert from uint8 to float32 in range [0,1]
# L1, R1, L2, R2 = load_path_dataset(selected_imgs)
# datagen  = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255.0)

# dt0 = datagen.flow_from_directory(L1, class_mode=None,
#                                   batch_size=BATCH_SIZE,
#                                   color_mode="grayscale",
#                                   shuffle=True,
#                                   seed=60386,
#                                   target_size=(IMG_HEIGHT, IMG_WIDTH))

# dt1 = datagen.flow_from_directory(R1, class_mode=None,
#                                   batch_size=BATCH_SIZE,
#                                   color_mode="grayscale",
#                                   shuffle=True,
#                                   seed=60386,
#                                   target_size=(IMG_HEIGHT, IMG_WIDTH))

# dtt0 = datagen.flow_from_directory(L2, class_mode=None,
#                                        batch_size=BATCH_SIZE,
#                                        color_mode="grayscale",
#                                        shuffle=True,
#                                        seed=60386,
#                                        target_size=(IMG_HEIGHT, IMG_WIDTH))

# dtt1 = datagen.flow_from_directory(R2, class_mode=None,
#                                        batch_size=BATCH_SIZE,
#                                        color_mode="grayscale",
#                                        shuffle=True,
#                                        seed=60386,
#                                        target_size=(IMG_HEIGHT, IMG_WIDTH))





'''
def combine_gen(dt0, dt1, train_setting_flow):
    while True: #LR
        a = next(dt0)
        b = next(dt1)
        yield a, b
'''

def create_base_network(input_shape, k1=32):
    '''Base network to be shared (eq. to feature extraction).
    '''
    input = Input(shape=input_shape)

    encoded_t = Conv2D(k1, (3, 3), activation='elu', padding='same')(input)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded_t)

    encoded_t = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded_t)

    encoded_s = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded_s)

    encoded_skip = Conv2D(k1*2, (3, 3), activation='elu', padding='same')(encoded)
    encoded      = Conv2D(k1*4, (3, 3), activation='elu', padding='same')(encoded_skip)
    decoded      = Conv2D(k1*8, (3, 3), activation='elu', padding='same')(encoded)  # <- questa potrebbe essere relu+
    decoded      = Conv2D(k1*4, (3, 3), activation='elu', padding='same')(decoded)
    decoded      = Conv2D(k1*2, (3, 3), activation='elu', padding='same')(decoded)
    #decoded      = tf.keras.layers.add([decoded, encoded_skip])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded      = tf.keras.layers.add([decoded, encoded_s])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded      = tf.keras.layers.add([decoded, encoded_t])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    #decoded      = tf.keras.layers.add([decoded, encoded_t])

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded)
    return Model(input, decoded)


def create_base_network_v2(input_shape, k1=32):
    '''Base network to be shared (eq. to feature extraction).
    '''
    input = Input(shape=input_shape)

    #enc1
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(input)
    encoded_1 = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_1)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded_2 = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_2)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded_3 = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_3)

    encoded = Conv2D(k1*2, (3, 3), activation='elu', padding='same')(encoded)
    encoded = Conv2D(k1*4, (3, 3), activation='elu', padding='same')(encoded)
    decoded = Conv2D(k1*8, (3, 3), activation='elu', padding='same')(encoded)  # <- questa potrebbe essere relu+
    decoded = Conv2D(k1*4, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1*2, (3, 3), activation='elu', padding='same')(decoded)


    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_3])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_2])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded      = tf.keras.layers.add([decoded, encoded_1])

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded)

    return Model(input, decoded)


def create_base_network_v3(input_shape, k1=32):
    '''Base network to be shared (eq. to feature extraction).
    '''
    input = Input(shape=input_shape)

    #enc1
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(input)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded_2 = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_2)

    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded_3 = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded   = MaxPooling2D((2, 2), padding='same')(encoded_3)

    encoded = Conv2D(k1*2, (3, 3), activation='elu', padding='same')(encoded)
    encoded = Conv2D(k1*4, (3, 3), activation='elu', padding='same')(encoded)
    decoded = Conv2D(k1*8, (3, 3), activation='elu', padding='same')(encoded)  # <- questa potrebbe essere relu+
    decoded = Conv2D(k1*4, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1*2, (3, 3), activation='elu', padding='same')(decoded)


    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_3])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_2])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded)

    return Model(input, decoded)


def create_base_network2(input_shape, k1=32):
    '''Base network to be shared (eq. to feature extraction).
    '''
    input = Input(shape=input_shape)

    encoded_t = Conv2D(k1, (3, 3), activation='elu', padding='same')(input)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded_t)

    encoded_t = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded_t)

    encoded_s = Conv2D(k1, (3, 3), activation='elu', padding='same')(encoded)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded_s)

    encoded_skip = Conv2D(k1 * 2, (3, 3), activation='elu', padding='same')(encoded)
    encoded = Conv2D(k1 * 4, (3, 3), activation='elu', padding='same')(encoded_skip)
    decoded = Conv2D(k1 * 8, (3, 3), activation='elu', padding='same')(encoded)  # <- questa potrebbe essere relu+
    decoded = Conv2D(k1 * 4, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(k1 * 2, (3, 3), activation='elu', padding='same')(decoded)
    # decoded      = tf.keras.layers.add([decoded, encoded_skip])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_s])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    decoded = tf.keras.layers.add([decoded, encoded_t])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(k1, (3, 3), activation='elu', padding='same')(decoded)
    # decoded      = tf.keras.layers.add([decoded, encoded_t])

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded)
    return Model(input, decoded)







def simple_network(input_shape, k1=32):

    input_img = Input(shape=input_shape)

    encoded = Conv2D(32, (3, 3), activation='elu', padding='same')(input_img)
    encoded = MaxPooling2D((2, 2), padding='same')(encoded)

    encoded = Conv2D(32, (3, 3), activation='elu', padding='same')(encoded)
    encoded_skip = MaxPooling2D((2, 2), padding='same')(encoded)

    encoded = Conv2D(32, (3, 3), activation='elu', padding='same')(encoded_skip)

    encoded = Conv2D(64, (3, 3), activation='elu', padding='same')(encoded)
    encoded = Conv2D(128, (3, 3), activation='elu', padding='same')(encoded)
    decoded = Conv2D(256, (3, 3), activation='elu', padding='same')(encoded)  # <- questa potrebbe essere relu+
    decoded = Conv2D(128, (3, 3), activation='elu', padding='same')(decoded)
    decoded = Conv2D(64, (3, 3), activation='elu', padding='same')(decoded)

    decoded = Conv2D(32, (3, 3), activation='elu', padding='same')(decoded)  # additional layer
    decoded = tf.keras.layers.add([decoded, encoded_skip])

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(32, (3, 3), activation='elu', padding='same')(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded = Conv2D(32, (3, 3), activation='elu', padding='same')(decoded)

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded)
    return Model(input_img, decoded)


# ## SSIM
# def ssi_loss(y_true, y_pred):
#  max_max = tf.reduce_max(tf.stack([tf.reduce_max(y_true), tf.reduce_max(y_pred)], 0))
#  return   1.0 - tf.reduce_mean(tf.image.ssim(y_true, y_pred, max_val=max_max, filter_size=3, filter_sigma=1.5, k1=0.01, k2=0.03))

# def ssi_acc(y_true, y_pred):
#  max_max = tf.reduce_max(tf.stack([tf.reduce_max(y_true), tf.reduce_max(y_pred)], 0))
#  return  tf.reduce_mean(tf.image.ssim(y_true, y_pred, max_val=max_max, filter_size=3, filter_sigma=1.5, k1=0.01, k2=0.03))

# ## SSIM Multiscale
# def ssi_loss_ms(y_true, y_pred):
#  max_max = tf.reduce_max(tf.stack([tf.reduce_max(y_true), tf.reduce_max(y_pred)], 0))
#  return 1.0 - tf.reduce_mean(tf.image.ssim_multiscale(y_true, y_pred, max_val=max_max, filter_size=3, power_factors=[(0.0448, 0.2856, 0.3001, 0.2363, 0.1333)] ))

# def ssi_acc_ms(y_true, y_pred):
#  max_max = tf.reduce_max(tf.stack([tf.reduce_max(y_true), tf.reduce_max(y_pred)], 0))
#  return tf.reduce_mean(tf.image.ssim_multiscale(y_true, y_pred, max_val=max_max, filter_size=3, power_factors=[(0.0448, 0.2856, 0.3001, 0.2363, 0.1333)] ))


# #Contrastive Loss
# #def acc_contrastive(y_true, y_pred):
# #   con_loss =tf.reduce_mean(tfa.losses.contrastive_loss(y_true, y_pred, 1.0))
# #   return  1.0 - con_loss


# #def loss_contrastive(y_true, y_pred):
# #    con_loss = tf.reduce_mean(tfa.losses.contrastive_loss(y_true, y_pred, 1.0))
# #    return con_loss

# #Smooth loss
# def loss_smooth(y_true, y_pred):
#     dy_true, dx_true = tf.image.image_gradients(y_true)
#     dy_pred, dx_pred = tf.image.image_gradients(y_pred)
#     l_edges = tf.reduce_mean(tf.abs(dy_pred - dy_true) + tf.abs(dx_pred - dx_true), axis=-1)
#     return l_edges

# def acc_smooth(y_true, y_pred):
#     dy_true, dx_true = tf.image.image_gradients(y_true)
#     dy_pred, dx_pred = tf.image.image_gradients(y_pred)
#     l_edges = tf.reduce_mean(tf.abs(dy_pred - dy_true) + tf.abs(dx_pred - dx_true), axis=-1)
#     return 1.0 - l_edges

# #Depth-wise loss #Also colled L1 consistency loss
# def loss_depth_wise(y_true, y_pred):
#     l_depth = tf.reduce_mean(tf.abs(y_pred - y_true), axis=-1)
#     return l_depth

# def acc_depth_wise(y_true, y_pred):
#     l_depth = tf.reduce_mean(tf.abs(y_pred - y_true), axis=-1)
#     return 1.0 - l_depth


# def loss_final(y_true, y_pred):
#     return alpha1 * ssi_loss(y_true, y_pred) + alpha2 * loss_smooth(y_true, y_pred) + alpha3 * loss_depth_wise(y_true, y_pred)

# def acc_final(y_true, y_pred):
#     return 1.0 - (alpha1 * ssi_loss(y_true, y_pred) + alpha2 * loss_smooth(y_true, y_pred) + alpha3 * loss_depth_wise(y_true, y_pred))





# #Convex combination of the losses above
# def convex_comb_loss(alpha1, alpha2, alpha3):
#     def loss_final(y_true, y_pred):
#         return alpha1 * ssi_loss(y_true, y_pred) + alpha2 * loss_smooth(y_true, y_pred) + alpha3 * loss_depth_wise(y_true, y_pred)
#     return loss_final

# def convex_comb_acc(alpha1, alpha2, alpha3):
#     def acc_final(y_true, y_pred):
#         return 1.0 - (alpha1 * ssi_loss(y_true, y_pred) + alpha2 * loss_smooth(y_true, y_pred) + alpha3 * loss_depth_wise(y_true, y_pred))
#     return acc_final






# def step_decay(epoch):
#    #hamlyin center settings
#    initial_lrate = 0.0001
#    drop = 0.5
#    epochs_drop = 5.0
#    lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))
#    return lrate







# def combine_gen(dt0, dt1,train_setting_flow):
#     if train_setting_flow == 0:
#         while True: #LR
#             a = next(dt0)
#             b = next(dt1)
#             yield a, b
#     elif train_setting_flow == 1:
#         while True: #RL
#             a = next(dt0)
#             b = next(dt1)
#             yield b, a
#     elif train_setting_flow == 2:
#         while True: #LR - L
#             a = next(dt0)
#             b = next(dt1)
#             yield (a,b), (b,a)
#     elif train_setting_flow == 3:
#         while True: #RL - R
#             a = next(dt0)
#             b = next(dt1)
#             yield (b, a), (a,b)





# stereo_pair_train = combine_gen( dt0,  dt1, train_setting_flow)
# stereo_pair_test  = combine_gen(dtt0, dtt1, train_setting_flow)

# #input
# input_shape = (IMG_HEIGHT, IMG_WIDTH, 1)

# #define personalized loss
# cc_loss =  convex_comb_loss(alpha1, alpha2, alpha3)
# cc_acc  =  convex_comb_acc(alpha1, alpha2, alpha3)


# if learning_rate_decay == 1:
#     print("--- Model running with learning rate decay ---")
#     decay_rate = LEARNING_RATE / EPOCHS*2
#     opt = tf.keras.optimizers.Adadelta(learning_rate=LEARNING_RATE, rho=0.95, epsilon=1e-07, decay= decay_rate, name='adadelta')
# else:
#     opt = tf.keras.optimizers.Adadelta(learning_rate=LEARNING_RATE, rho=0.95, epsilon=1e-07, name='adadelta')

# name_folder, _, tb_callback, checkpoint_path, _, cp_callback, model_path = tensor_checkpoints_and_retrain(args.exp_name, continue_fit)

# if learning_rate_plateau ==1:
#     print("--- Model running with reduce learning on plateau ---")
#     reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='cc_loss', verbose=1, factor=decay_factor, mode='min', patience=patience_lr, min_lr=0.000000000000000000001)


# # Open a strategy scope.
# with strategy.scope():
#   if train_setting_flow == 2 or train_setting_flow==3:
#       print("-- Siamese running --")
#       input_a = Input(shape=input_shape)
#       input_b = Input(shape=input_shape)

#       if shared_model == 0:
#           print("--- Siamese Weights Shared Model ---")
#           base_network = create_base_network(input_shape, k1)
#           print(base_network.summary())
#           processed_a = base_network(input_a)
#           processed_b = base_network(input_b)
#       elif shared_model == 11:
#           print("--- Siamese Weights Shared Model v2 ---")
#           base_network = create_base_network_v2(input_shape, k1)
#           processed_a = base_network(input_a)
#           processed_b = base_network(input_b)
#       elif shared_model == 12:
#           print("--- Siamese Weights Shared Model v3 -- Less Skip ---")
#           base_network = create_base_network_v3(input_shape, k1)
#           processed_a = base_network(input_a)
#           processed_b = base_network(input_b)
#       elif shared_model == 1:
#           print("--- Siamese Weights Unshared Model ---")
#           base_network_left = create_base_network(input_shape, k1)
#           base_network_right = create_base_network2(input_shape, k1)
#           processed_a = base_network_left(input_a)
#           processed_b = base_network_right(input_b)
#       else:
#           print("--- Siamese with already Learned Branches ---")
#           LR_network = load_LR_net('pretrain/LR/139.hdf5')
#           RL_network = load_RL_net('pretrain/RL/139.hdf5')
#           input_a = Input(shape=input_shape)
#           input_b = Input(shape=input_shape)
#           processed_a = LR_network(input_a, training=False)
#           processed_b = RL_network(input_b, training=False)
#           print(processed_a.shape)
#           print(processed_b.shape)
#           #processed_a = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x_LR)
#           #processed_b = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x_RL)

#       concat_proc = Concatenate(axis=-1)([processed_a, processed_b])
#       concat_proc = Dense(d1, activation='elu', kernel_regularizer=tf.keras.regularizers.l1(0.01), bias_regularizer=tf.keras.regularizers.l1(0.01))(concat_proc)
#       concat_proc = Dense(d1, activation='elu', kernel_regularizer=tf.keras.regularizers.l1(0.01), bias_regularizer=tf.keras.regularizers.l1(0.01))(concat_proc)
#       concat_proc = Dense(d1, activation='elu', kernel_regularizer=tf.keras.regularizers.l1(0.01), bias_regularizer=tf.keras.regularizers.l1(0.01))(concat_proc)
#       concat_proc = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(concat_proc)
#       autoencoder = Model([input_a, input_b], [concat_proc])
#       print(autoencoder.summary())

#   elif train_setting_flow == 0 or train_setting_flow ==1:
#       print("--- Single Branch Model ---")
#       if simple_model == 0:
#         print("--- Model with 2 Skip conn ---")
#         autoencoder = create_base_network(input_shape, k1)
#       if simple_model == 2:
#         print("--- Hamlyn Center ---")
#         autoencoder = hamy_network(input_shape, k1)
#       if simple_model ==3:
#         print("--- umm")
#         autoencoder = create_res_network(input_shape, k1)
#         print(autoencoder.summary())
#       else:
#         print("--- Model with 1 Skip conn ---")
#         autoencoder = simple_network(input_shape, 32) #less accurate

#   autoencoder.compile(optimizer=opt, loss=cc_loss, metrics=[ssi_acc, cc_acc, 'mse'])

# #print(autoencoder.summary())



# autoencoder.save_weights(checkpoint_path.format(epoch=0, ssi_acc=0))



# if continue_fit != '0':
#     print("enter in continue fit...")
#     all_subdirs = all_subdirs_of('checkpoints')
#     latest_subdir = max(all_subdirs, key=os.path.getmtime).split('/')
#     name_folder = latest_subdir  + "/" +  continue_fit  + ".hdf5"
#     autoencoder = tf.keras.models.load_model(name_folder,
#                                              custom_objects={'cc_loss': cc_loss,
#                                                              'ssi_acc': ssi_acc,
#                                                              'cc_acc' : cc_acc})

#     autoencoder.fit(stereo_pair_train,
#                 steps_per_epoch=LEFT_RIGHT_TRAIN // BATCH_SIZE,
#                 epochs=EPOCHS,
#                 shuffle=True,
#                 validation_data=stereo_pair_test,
#                 validation_steps=LEFT_RIGHT_TEST // BATCH_SIZE,
#                 callbacks=[ cp_callback, tb_callback],
#                 verbose=1 )
# else:
#     autoencoder.fit(stereo_pair_train,
#                 steps_per_epoch=LEFT_RIGHT_TRAIN//BATCH_SIZE,
#                 epochs=EPOCHS,
#                 shuffle=True,
#                 validation_data= stereo_pair_test,
#                 validation_steps=LEFT_RIGHT_TEST//BATCH_SIZE,
#                 callbacks = [cp_callback, tb_callback],
#                 verbose=1 )

#     '''lrate = LearningRateScheduler(step_decay)  #this is lrate with step decay
#     autoencoder.fit(stereo_pair_train,
#                 steps_per_epoch=LEFT_RIGHT_TRAIN//BATCH_SIZE,
#                 epochs=EPOCHS,
#                 shuffle=True,
#                 validation_data= stereo_pair_test,
#                 validation_steps=LEFT_RIGHT_TEST//BATCH_SIZE,
#                 callbacks = [lrate, cp_callback, tb_callback],
#                 verbose=1 )'''


# #autoencoder.save(model_path)
# print(name_folder)

def hamy_network(input_shape, k1=32):
    input = Input(shape=input_shape)
    #conv1
    encoded  = Conv2D(64, (3, 3), activation='elu', padding='same')(input)
    encoded  = Conv2D(64, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)
    #conv2
    encoded  = Conv2D(128, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(128, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)
    #conv3
    encoded  = Conv2D(256, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(256, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(256, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)
    #conv4
    encoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)

    #conv5
    encoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)
    encoded  = MaxPooling2D((2, 2), padding='same')(encoded)

    decoded = Conv2D(512, (3, 3), activation='elu', padding='same')(encoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(512, (3, 3), activation='elu', padding='same')(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(256, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(256, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(256, (3, 3), activation='elu', padding='same')(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(128, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(128, (3, 3), activation='elu', padding='same')(decoded)

    decoded = UpSampling2D((2, 2), interpolation='nearest')(decoded)
    decoded  = Conv2D(64, (3, 3), activation='elu', padding='same')(decoded)
    decoded  = Conv2D(64, (3, 3), activation='elu', padding='same')(decoded)

    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded)
    return Model(input, decoded)


model = hamy_network((128, 128, 3))
model.summary()

print(depth_model.count_params())
print(len(depth_model.layers))

tf.keras.utils.plot_model(
    depth_model,
    show_shapes=True,
    show_dtype=False,
    show_layer_names=False,
    rankdir='TB',
    expand_nested=True,
    dpi=100,
    show_layer_activations=False,
    show_trainable=False)

from tensorflow.keras.layers import Conv2D, UpSampling2D, LeakyReLU, Concatenate
from tensorflow.keras import Model
from tensorflow.keras.applications import DenseNet169

class UpscaleBlock(Model):
    def __init__(self, filters, name):
        super(UpscaleBlock, self).__init__()
        self.up = UpSampling2D(size=(2, 2), interpolation='bilinear', name=name+'_upsampling2d')
        self.concat = Concatenate(name=name+'_concat') # Skip connection
        self.convA = Conv2D(filters=filters, kernel_size=3, strides=1, padding='same', name=name+'_convA')
        self.reluA = LeakyReLU(negative_slope=0.2)
        self.convB = Conv2D(filters=filters, kernel_size=3, strides=1, padding='same', name=name+'_convB')
        self.reluB = LeakyReLU(negative_slope=0.2)

    def call(self, x):
        b = self.reluB( self.convB( self.reluA( self.convA( self.concat( [self.up(x[0]), x[1]] ) ) ) ) )
        return b

class Encoder(Model):
    def __init__(self):
        super(Encoder, self).__init__()
        self.base_model = DenseNet169(input_shape=(192, 256, 3), include_top=False, weights='imagenet', name='base_model')
        print('Base model loaded {}'.format(DenseNet169.__name__))

        # Create encoder model that produce final features along with multiple intermediate features
        outputs = [self.base_model.outputs[-1]]
        for name in ['pool1', 'pool2_pool', 'pool3_pool', 'conv1_relu'] : outputs.append( self.base_model.get_layer(name).output )
        print(self.base_model.inputs)
        self.encoder = Model(inputs=self.base_model.inputs, outputs=outputs)

    def call(self, x):
        return self.encoder(x)

class Decoder(Model):
    def __init__(self, decode_filters):
        super(Decoder, self).__init__()
        self.conv2 =  Conv2D(filters=decode_filters, kernel_size=1, padding='same', name='conv2')
        self.up1 = UpscaleBlock(filters=decode_filters//2,  name='up1')
        self.up2 = UpscaleBlock(filters=decode_filters//4,  name='up2')
        self.up3 = UpscaleBlock(filters=decode_filters//8,  name='up3')
        self.up4 = UpscaleBlock(filters=decode_filters//16, name='up4')
        self.conv3 = Conv2D(filters=1, kernel_size=3, strides=1, padding='same', name='conv3')

    def call(self, features):
        x, pool1, pool2, pool3, conv1 = features[0], features[1], features[2], features[3], features[4]
        up0 = self.conv2(x)
        up1 = self.up1([up0, pool3])
        up2 = self.up2([up1, pool2])
        up3 = self.up3([up2, pool1])
        up4 = self.up4([up3, conv1])
        return self.conv3( up4 )

class DepthEstimate(Model):
    def __init__(self):
        super(DepthEstimate, self).__init__()
        self.encoder = Encoder()
        self.decoder = Decoder( decode_filters = int(self.encoder.layers[-1].output[0].shape[-1] // 2 ) )
        print('\nModel created.')

    def call(self, x):
        return self.decoder( self.encoder(x) )

"""# PAPER 3: [Deep Vision-Based Framework for Coastal Flood Prediction Under Climate Change Impacts and Shoreline Adaptations](https://github.com/Arnukk/CASPIAN)"""

cd /content/CASPIAN

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, Concatenate, LeakyReLU, BatchNormalization, MaxPool2D, ReLU, Activation, MaxPooling2D, AveragePooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D, Add, concatenate, Dropout
from tensorflow.keras.initializers import RandomNormal, HeNormal, VarianceScaling, HeUniform, GlorotUniform, GlorotNormal

"""## CASPIAN"""

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, Concatenate, LeakyReLU, BatchNormalization, MaxPool2D, ReLU, Activation, MaxPooling2D, AveragePooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D, Add, concatenate, Dropout
from tensorflow.keras import layers
from tensorflow.keras.initializers import GlorotNormal

# Assuming resnetxt_block is defined elsewhere,
# for this example, I'll provide a placeholder.
def resnetxt_block(x, filters, cardinality, init, activation):
    # This is a placeholder; replace with your actual resnetxt_block implementation
    # Make sure operations inside are Keras layers/operations or wrapped in Lambda.
    y = layers.Conv2D(filters, (1, 1), padding="same", kernel_initializer=GlorotNormal(seed=42))(x)
    y = layers.BatchNormalization()(y)
    y = layers.Activation(activation)(y)
    # Grouped convolutions or other logic for ResNeXt
    y = layers.Conv2D(filters, (3, 3), padding="same", kernel_initializer=GlorotNormal(seed=42))(y)
    y = layers.BatchNormalization()(y)
    y = layers.Activation(activation)(y)
    y = layers.Conv2D(x.shape[-1], (1, 1), padding="same", kernel_initializer=GlorotNormal(seed=42))(y) # Match input channels for residual
    y = layers.BatchNormalization()(y)
    x = layers.add([x, y])
    x = layers.Activation(activation)(x)
    return x

# def CASPIAN(input_shape=(192, 256, 3), filters=256, cardinality=36, activation='tanh', init="glorot_normal",
#             input_centering=True, depth=4, bottleneck_depth=8, compression_factor=0.9, gr_level=4, sup_level=1):

def CASPIAN(input_shape=(192, 256, 3), filters=256, cardinality=36, activation='tanh', init="glorot_normal",
            input_centering=True, depth=4, bottleneck_depth=8, compression_factor=0.9, gr_level=2, sup_level=1):

    input_grid = layers.Input(shape=input_shape)

    if input_centering:
        # Create a Lambda layer to replace 0.5 with -1
        replace_half_with_negative_one = layers.Lambda(
            lambda x: tf.where(tf.equal(x, 0.5), tf.constant(-1.0, dtype=x.dtype), x)
        )
        x = replace_half_with_negative_one(input_grid)
    else:
        x = input_grid

    # Encoder
    pools = []
    for i in range(depth):
        if i == 0:
            #Entry block
            pool_size = 2
            s = layers.Conv2D(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=GlorotNormal(seed=42))(x)
            #Stratified Pooling
            if input_centering:
                mask_neg_one = layers.Lambda(
                    lambda x_in: tf.where(tf.equal(x_in, -1.0), x_in, tf.zeros_like(x_in))
                )(x) # Pass x to the lambda layer
                mask_pos_one = layers.Lambda(
                    lambda x_in: tf.where(tf.equal(x_in, 1.0), x_in, tf.zeros_like(x_in))
                )(x) # Pass x to the lambda layer
            else:
                mask_half = layers.Lambda(
                    lambda x_in: tf.where(tf.equal(x_in, 0.5), x_in, tf.zeros_like(x_in))
                )(x) # Pass x to the lambda layer
                mask_pos_one = layers.Lambda(
                    lambda x_in: tf.where(tf.equal(x_in, 1.0), x_in, tf.zeros_like(x_in))
                )(x) # Pass x to the lambda layer

            if input_centering:
                p = layers.concatenate([mask_neg_one, mask_pos_one], axis=-1)
            else:
                p = layers.concatenate([mask_half, mask_pos_one], axis=-1)

            p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(p)
            pools.append(p)
            x = layers.concatenate([s, p], axis=-1)
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=GlorotNormal(seed=42))(x)
            x = layers.add([s, x])
            x = layers.Activation(activation)(x)
        else:
            # Downsampling block with Depthwise convs.
            s = x
            d = layers.DepthwiseConv2D(depth_multiplier=1, kernel_size=(2, 2), strides=(2, 2), padding="same", activation=activation, depthwise_initializer=GlorotNormal(seed=42))(x)
            p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(pools[-1])
            pools.append(p)
            x = layers.concatenate([d, p], axis=-1)
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=GlorotNormal(seed=42))(x)
            b = layers.Conv2D(filters, (1, 1), strides=(2, 2), padding="same", activation=None, kernel_initializer=GlorotNormal(seed=42))(s)
            x = layers.add([b, x])
            x = layers.Activation(activation)(x)

    # Information Bottleneck layer
    for _ in range(bottleneck_depth):
        x = resnetxt_block(x, filters=filters, cardinality=cardinality, init=GlorotNormal(seed=42), activation=activation)

    # Decoder
    the_weights = None
    for i in range(depth - 1, -1, -1):
        # Pooling Supervised Upsampling block
        x = layers.Concatenate(axis=-1)([x, pools[i]])
        x = layers.Conv2DTranspose(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=init)(x)
        # Channel weights
        if sup_level != 0:
            # Use Lambda layer for tf.math.reduce_sum
            p_sum = layers.Lambda(lambda t: tf.math.reduce_sum(t, axis=-1, keepdims=True))(pools[i])
            p = layers.AveragePooling2D(pool_size=(gr_level, gr_level), strides=(gr_level, gr_level), padding='same')(p_sum)
            spatial_encoding_flattened = layers.Flatten()(p)
            weights = layers.Dense(int(compression_factor * filters), activation=activation, kernel_initializer=init)(spatial_encoding_flattened)
            weights = layers.Dense(filters, activation='sigmoid', kernel_initializer=init)(weights)
            weights_reshaped = layers.Reshape((1, 1, filters))(weights)
            the_weights = weights_reshaped
            sup_level = sup_level - 1
        else:
            weights_reshaped = the_weights
        unifying_convs = layers.Conv2D(filters, (1, 1), padding='same', kernel_initializer=init, activation=activation)(x)
        x = layers.Multiply()([unifying_convs, weights_reshaped])

    # Output head
    out = layers.Conv2D(1, kernel_size=(1, 1), strides=(1, 1), activation=None, padding='same', kernel_initializer=init)(x)

    # Use Lambda layer for tf.reduce_sum
    summed_features = layers.Lambda(lambda t: tf.reduce_sum(t, axis=-1, keepdims=True))(x)

    out = layers.add([summed_features, out])
    out = layers.Activation('relu')(out)

    model = tf.keras.models.Model(inputs=input_grid, outputs=out)

    return model

model = CASPIAN()
model.summary()

# !pip install visualkeras

import visualkeras
visualkeras.layered_view(model, legend=True)

######################################################################################################################################
############### CASPIAN ##############################################################################################################
######################################################################################################################################

def resnetxt_block(x, filters, cardinality=32, bottleneck_width=4, strides=1, activation='tanh', init="glorot_normal", kernel=3):
    # Shortcut connection
    shortcut = x
    # Compute the width of each group (path)
    group_width = bottleneck_width * cardinality
    # 1x1 Convolution
    x = layers.Conv2D(group_width, (1, 1), padding='same', strides=strides, activation=activation, kernel_initializer=init)(x)
    # Grouped 3x3 Convolution
    x = layers.Conv2D(group_width, (kernel, kernel), padding='same', strides=1, groups=cardinality, activation=activation, kernel_initializer=init)(x)
    #x = SpatialDropout2D(0.2)(x)
    # 1x1 Convolution
    x = layers.Conv2D(filters, (1, 1), padding='same', strides=1, kernel_initializer=init)(x)
    # Adjust the shortcut path if needed
    if strides != 1 or x.shape[-1] != shortcut.shape[-1]:
        shortcut = layers.Conv2D(filters, (1, 1), strides=strides)(shortcut)
    # Element-wise addition
    x = layers.add([shortcut, x])
    x = layers.Activation(activation)(x)
    return x


def CASPIAN(input_shape=(1024, 1024, 1), filters=81, cardinality=36, activation='tanh', init="glorot_normal",
                    input_centering=True, depth=4, bottleneck_depth=8, compression_factor=0.9, gr_level=4, sup_level=1):

    input_grid = layers.Input(shape=input_shape)

    if input_centering:
        # Create a Lambda layer to replace 0.5 with -1
        replace_half_with_negative_one = layers.Lambda(
            lambda x: tf.where(tf.equal(x, 0.5), tf.constant(-1.0, dtype=x.dtype), x)
        )
        x = replace_half_with_negative_one(input_grid)
    else:
        x = input_grid

    # Encoder
    pools = []
    for i in range(depth):
        if i == 0:
            #Entry block
            pool_size=2
            s = layers.Conv2D(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=init)(x)
            #Stratified Pooling
            if input_centering:
                mask =  layers.Lambda(
                    lambda x: tf.where(tf.equal(x, -1), x, tf.zeros_like(x))
                )
            else:
                mask =  layers.Lambda(
                    lambda x: tf.where(tf.equal(x, 0.5), x, tf.zeros_like(x))
                )
            pool_1 = mask(x)
            mask =  layers.Lambda(
                    lambda x: tf.where(tf.equal(x, 1), x, tf.zeros_like(x))
            )
            pool_2 = mask(x)
            p = layers.concatenate([pool_1, pool_2], axis=-1)
            p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(p)
            pools.append(p)
            x = layers.concatenate([s, p], axis=-1)
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=init)(x)
            x = layers.add([s, x])
            x = layers.Activation(activation)(x)
        else:
            # Downsampling block with Depthwise convs.
            s = x
            d = layers.DepthwiseConv2D(depth_multiplier=1, kernel_size=(2, 2), strides=(2, 2), padding="same", activation=activation, kernel_initializer=init)(x)
            p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(pools[-1])
            pools.append(p)
            x = layers.concatenate([d, p], axis=-1)
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=init)(x)
            b = layers.Conv2D(filters, (1, 1), strides=(2, 2), padding="same", activation=None, kernel_initializer=init)(s)
            x = layers.add([b, x])
            x = layers.Activation(activation)(x)

        # Information Bottleneck layer
    for _ in range(bottleneck_depth):
        x = resnetxt_block(x, filters=filters, cardinality=cardinality, init=init, activation=activation)

    # Decoder
    the_weights = None
    for i in range(depth-1, -1, -1):
        # Pooling Supervised Upsampling block
        x = layers.Concatenate(axis=-1)([x, pools[i]])
        x = layers.Conv2DTranspose(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=init)(x)
        # Channel weights
        if sup_level != 0:
            p = tf.reduce_sum(pools[i], axis=-1, keepdims=True)
            p = layers.AveragePooling2D(pool_size=(gr_level, gr_level), strides=(gr_level, gr_level), padding='same')(p)
            #p = tf.reduce_sum(p, axis=-1, keepdims=True)
            spatial_encoding_flattened = layers.Flatten()(p)
            weights = layers.Dense(int(compression_factor*filters), activation=activation, kernel_initializer=init)(spatial_encoding_flattened)
            weights = layers.Dense(filters, activation='sigmoid', kernel_initializer=init)(weights)
            weights_reshaped = layers.Reshape((1, 1, filters))(weights)
            the_weights = weights_reshaped
            sup_level = sup_level -1
        else:
            weights_reshaped = the_weights
        unifying_convs = layers.Conv2D(filters, (1, 1), padding='same', kernel_initializer=init, activation=activation)(x)
        x = tf.keras.layers.Multiply()([unifying_convs, weights_reshaped])

    # Output head
    out = layers.Conv2D(1, kernel_size=(1, 1), strides=(1, 1), activation=None, padding='same', kernel_initializer=init)(x)

    summed_features = tf.reduce_sum(x, axis=-1, keepdims=True)

    out = layers.add([summed_features, out])
    out = layers.Activation('relu')(out)

    model = tf.keras.models.Model(inputs=input_grid, outputs=out)

    return model

######################################################################################################################################
############### CASPIAN END  #########################################################################################################
######################################################################################################################################



######################################################################################################################################
############### FOR ABLATION STUDIES #################################################################################################
######################################################################################################################################

def CASPIAN_beta(input_shape=(1024, 1024, 1), filters=81, cardinality=36, activation='tanh', init="glorot_normal",
                    input_centering=True, depth=4, bottleneck_depth=8, compression_factor=0.9, gr_level=4, sup_level=1, version=1):

    if version == 4:
      bottleneck_depth = 2

    input_grid = layers.Input(shape=input_shape)

    if input_centering:
        # Create a Lambda layer to replace 0.5 with -1
        replace_half_with_negative_one = layers.Lambda(
            lambda x: tf.where(tf.equal(x, 0.5), tf.constant(-1.0, dtype=x.dtype), x)
        )
        x = replace_half_with_negative_one(input_grid)
    else:
        x = input_grid

    # Encoder
    pools = []
    for i in range(depth):
        if i == 0:
            #Entry block
            pool_size=2
            s = layers.Conv2D(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=init)(x)
            if version != 3:
              #Stratified Pooling
              if input_centering:
                  mask =  layers.Lambda(
                      lambda x: tf.where(tf.equal(x, -1), x, tf.zeros_like(x))
                  )
              else:
                  mask =  layers.Lambda(
                      lambda x: tf.where(tf.equal(x, 0.5), x, tf.zeros_like(x))
                  )
              pool_1 = mask(x)
              mask =  layers.Lambda(
                      lambda x: tf.where(tf.equal(x, 1), x, tf.zeros_like(x))
              )
              pool_2 = mask(x)
              p = layers.concatenate([pool_1, pool_2], axis=-1)
              p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(p)
              pools.append(p)
              x = layers.concatenate([s, p], axis=-1)
            else:
              x = s
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=init)(x)
            x = layers.add([s, x])
            x = layers.Activation(activation)(x)
        else:
            # Downsampling block with Depthwise convs.
            s = x
            d = layers.DepthwiseConv2D(depth_multiplier=1, kernel_size=(2, 2), strides=(2, 2), padding="same", activation=activation, kernel_initializer=init)(x)
            if version != 3:
              p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(pools[-1])
              pools.append(p)
              x = layers.concatenate([d, p], axis=-1)
            else:
              x = d
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=init)(x)
            b = layers.Conv2D(filters, (1, 1), strides=(2, 2), padding="same", activation=None, kernel_initializer=init)(s)
            x = layers.add([b, x])
            x = layers.Activation(activation)(x)

        # Information Bottleneck layer
    for _ in range(bottleneck_depth):
        x = resnetxt_block(x, filters=filters, cardinality=cardinality, init=init, activation=activation)

    # Decoder
    the_weights = None
    for i in range(depth-1, -1, -1):
        # Pooling Supervised Upsampling block
        if version != 3:
          x = layers.Concatenate(axis=-1)([x, pools[i]])
        x = layers.Conv2DTranspose(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=init)(x)
        # Channel weights
        if version != 2 and version != 3:
          if sup_level != 0:
              p = tf.reduce_sum(pools[i], axis=-1, keepdims=True)
              p = layers.AveragePooling2D(pool_size=(gr_level, gr_level), strides=(gr_level, gr_level), padding='same')(p)
              #p = tf.reduce_sum(p, axis=-1, keepdims=True)
              spatial_encoding_flattened = layers.Flatten()(p)
              weights = layers.Dense(int(compression_factor*filters), activation=activation, kernel_initializer=init)(spatial_encoding_flattened)
              weights = layers.Dense(filters, activation='sigmoid', kernel_initializer=init)(weights)
              weights_reshaped = layers.Reshape((1, 1, filters))(weights)
              the_weights = weights_reshaped
              sup_level = sup_level -1
          else:
              weights_reshaped = the_weights
          unifying_convs = layers.Conv2D(filters, (1, 1), padding='same', kernel_initializer=init, activation=activation)(x)
          x = tf.keras.layers.Multiply()([unifying_convs, weights_reshaped])
        else:
          x = layers.Conv2D(filters, (1, 1), padding='same', kernel_initializer=init, activation=activation)(x)

    # Output head
    out = layers.Conv2D(1, kernel_size=(1, 1), strides=(1, 1), activation=None, padding='same', kernel_initializer=init)(x)

    if version != 1:
      summed_features = tf.reduce_sum(x, axis=-1, keepdims=True)
      out = layers.add([summed_features, out])

    out = layers.Activation('relu')(out)

    model = tf.keras.models.Model(inputs=input_grid, outputs=out)

    return model

######################################################################################################################################
############### ABLATION STUDIES END##################################################################################################
######################################################################################################################################

"""## Swin_unet"""

from __future__ import absolute_import

import tensorflow as tf
from tensorflow.keras.layers import Layer

def drop_path_(inputs, drop_prob, is_training):

    # Bypass in non-training mode
    if (not is_training) or (drop_prob == 0.):
        return inputs

    # Compute keep_prob
    keep_prob = 1.0 - drop_prob

    # Compute drop_connect tensor
    input_shape = tf.shape(inputs)
    batch_num = input_shape[0]; rank = len(input_shape)

    shape = (batch_num,) + (1,) * (rank - 1)
    random_tensor = keep_prob + tf.random.uniform(shape, dtype=inputs.dtype)
    path_mask = tf.floor(random_tensor)
    output = tf.math.divide(inputs, keep_prob) * path_mask
    return output

class drop_path(Layer):
    def __init__(self, drop_prob=None):
        super().__init__()
        self.drop_prob = drop_prob

    def call(self, x, training=None):
        return drop_path_(x, self.drop_prob, training)


from __future__ import absolute_import

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Dropout, Conv2D, LayerNormalization
from tensorflow.keras.activations import softmax

import tensorflow as tf

def pad_to_multiple(x, multiple):
    # x is a 4D tensor (B, H, W, C)
    # Get dynamic shapes for runtime operations
    B, H, W, C = tf.shape(x)

    pad_H = (multiple - H % multiple) % multiple
    pad_W = (multiple - W % multiple) % multiple

    if pad_H > 0 or pad_W > 0:
        paddings = [[0, 0], [0, pad_H], [0, pad_W], [0, 0]]
        x = tf.pad(x, paddings, "CONSTANT") # Pad with zeros
    return x

def window_partition(x, window_size):
    # Lấy hình dạng tĩnh của đầu vào (sau khi đã padding nếu cần)
    # Hoặc có thể lấy hình dạng động nếu H, W không cố định
    B_static, H_static, W_static, C_static = x.get_shape().as_list()

    # Nếu Batch size có thể là None, hãy lấy nó từ tf.shape()
    # B = tf.shape(x)[0]
    # H, W, C = H_static, W_static, C_static # Nếu H, W, C luôn cố định
    # hoặc H, W, C = tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3] # Nếu H,W,C có thể thay đổi trong quá trình trace graph

    # Đối với hàm này, giả sử H, W, C là các giá trị cố định hoặc đã được đảm bảo chia hết sau padding.
    # Sử dụng giá trị tĩnh H_static, W_static, C_static ở đây
    H, W, C = H_static, W_static, C_static

    # Đảm bảo H và W chia hết cho window_size
    if H % window_size != 0 or W % window_size != 0:
        # Lỗi này không nên xảy ra nếu bạn đã padding trước đó.
        # Nếu xảy ra, có nghĩa là padding chưa hoạt động đúng hoặc bạn quên padding.
        raise ValueError(f"Input dimensions H={H} and W={W} must be divisible by window_size={window_size}. "
                         "Consider padding the input before calling window_partition.")

    patch_num_H = H // window_size
    patch_num_W = W // window_size

    # reshape tensor thành các cửa sổ
    # -1 sẽ tự động tính toán batch_size mới, bao gồm số lượng cửa sổ
    x = tf.reshape(x, shape=(-1, patch_num_H, window_size, patch_num_W, window_size, C))

    # Hoán vị các chiều để nhóm các cửa sổ lại với nhau
    x = tf.transpose(x, (0, 1, 3, 2, 4, 5)) # (batch_size, num_windows_h, num_windows_w, window_h, window_w, C)

    # Reshape thành một chuỗi các cửa sổ, mỗi cửa sổ là một tensor 3D
    windows = tf.reshape(x, shape=(-1, window_size, window_size, C))

    return windows

def window_reverse(windows, window_size, H, W, C):

    # Reshape a patch sequence to aligned patched
    patch_num_H = H//window_size
    patch_num_W = W//window_size
    x = tf.reshape(windows, shape=(-1, patch_num_H, patch_num_W, window_size, window_size, C))
    x = tf.transpose(x, perm=(0, 1, 3, 2, 4, 5))

    # Merge patches to spatial frames
    x = tf.reshape(x, shape=(-1, H, W, C))

    return x

class Mlp(tf.keras.layers.Layer):
    def __init__(self, filter_num, drop=0., name=''):

        super().__init__()

        # MLP layers
        self.fc1 = Dense(filter_num[0], name='{}_mlp_0'.format(name))
        self.fc2 = Dense(filter_num[1], name='{}_mlp_1'.format(name))

        # Dropout layer
        self.drop = Dropout(drop)

        # GELU activation
        self.activation = tf.keras.activations.gelu

    def call(self, x):

        # MLP --> GELU --> Drop --> MLP --> Drop
        x = self.fc1(x)
        self.activation(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)

        return x

class WindowAttention(tf.keras.layers.Layer):
    def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0, proj_drop=0., name=''):
        super().__init__()

        self.dim = dim  # number of input dimensions
        self.window_size = window_size  # size of the attention window
        self.num_heads = num_heads  # number of self-attention heads

        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** -0.5  # query scaling factor

        self.prefix = name

        # Layers
        self.qkv = Dense(dim * 3, use_bias=qkv_bias, name='{}_attn_qkv'.format(self.prefix))
        self.attn_drop = Dropout(attn_drop)
        self.proj = Dense(dim, name='{}_attn_proj'.format(self.prefix))
        self.proj_drop = Dropout(proj_drop)

    def build(self, input_shape):
        # zero initialization
        num_window_elements = (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1)
        self.relative_position_bias_table = self.add_weight(
            name='{}_attn_pos'.format(self.prefix),
            shape=(num_window_elements, self.num_heads),
            initializer=tf.initializers.Zeros(),
            trainable=True)

        # Indices of relative positions
        coords_h = np.arange(self.window_size[0])
        coords_w = np.arange(self.window_size[1])
        coords_matrix = np.meshgrid(coords_h, coords_w, indexing='ij')
        coords = np.stack(coords_matrix)
        coords_flatten = coords.reshape(2, -1)
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
        relative_coords = relative_coords.transpose([1, 2, 0])
        relative_coords[:, :, 0] += self.window_size[0] - 1
        relative_coords[:, :, 1] += self.window_size[1] - 1
        relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
        relative_position_index_np = relative_coords.sum(-1) # Store as NumPy array initially

        # --- FIX START ---
        def relative_position_index_initializer():
            return tf.convert_to_tensor(relative_position_index_np, dtype=tf.int64)

        self.relative_position_index = tf.Variable(
            initial_value=relative_position_index_initializer, # Pass the callable
            trainable=False,
            name='{}_attn_pos_ind'.format(self.prefix)
        )
        # --- FIX END ---

        self.built = True

    def call(self, x, mask=None):

        # Get input tensor static shape
        _, N, C = x.get_shape().as_list()
        head_dim = C // self.num_heads

        x_qkv = self.qkv(x)
        x_qkv = tf.reshape(x_qkv, shape=(-1, N, 3, self.num_heads, head_dim))
        x_qkv = tf.transpose(x_qkv, perm=(2, 0, 3, 1, 4))
        q, k, v = x_qkv[0], x_qkv[1], x_qkv[2]

        # Query rescaling
        q = q * self.scale

        # multi-headed self-attention
        k = tf.transpose(k, perm=(0, 1, 3, 2))
        attn = (q @ k)

        # Shift window
        num_window_elements = self.window_size[0] * self.window_size[1]
        relative_position_index_flat = tf.reshape(self.relative_position_index, shape=(-1,))
        relative_position_bias = tf.gather(self.relative_position_bias_table, relative_position_index_flat)
        relative_position_bias = tf.reshape(relative_position_bias, shape=(num_window_elements, num_window_elements, -1))
        relative_position_bias = tf.transpose(relative_position_bias, perm=(2, 0, 1))
        attn = attn + tf.expand_dims(relative_position_bias, axis=0)

        if mask is not None:
            nW = mask.get_shape()[0]
            mask_float = tf.cast(tf.expand_dims(tf.expand_dims(mask, axis=1), axis=0), tf.float32)
            attn = tf.reshape(attn, shape=(-1, nW, self.num_heads, N, N)) + mask_float
            attn = tf.reshape(attn, shape=(-1, self.num_heads, N, N))
            attn = softmax(attn, axis=-1)
        else:
            attn = softmax(attn, axis=-1)

        # Dropout after attention
        attn = self.attn_drop(attn)

        # Merge qkv vectors
        x_qkv = (attn @ v)
        x_qkv = tf.transpose(x_qkv, perm=(0, 2, 1, 3))
        x_qkv = tf.reshape(x_qkv, shape=(-1, N, C))

        # Linear projection
        x_qkv = self.proj(x_qkv)

        # Dropout after projection
        x_qkv = self.proj_drop(x_qkv)

        return x_qkv

# class SwinTransformerBlock(tf.keras.layers.Layer):
#     def __init__(self, dim, num_patch, num_heads, window_size=7, shift_size=0, num_mlp=1024,
#                  qkv_bias=True, qk_scale=None, mlp_drop=0, attn_drop=0, proj_drop=0, drop_path_prob=0, name='', **kwargs):
#         super().__init__(**kwargs)

#         self.dim = dim # number of input dimensions
#         self.num_patch = num_patch # number of embedded patches; a tuple of  (heigh, width)
#         self.num_heads = num_heads # number of attention heads
#         self.window_size = window_size # size of window
#         self.shift_size = shift_size # size of window shift
#         self.num_mlp = num_mlp # number of MLP nodes
#         self.qkv_bias = qkv_bias
#         self.qk_scale = qk_scale
#         self.mlp_drop = mlp_drop
#         self.attn_drop = attn_drop
#         self.proj_drop = proj_drop
#         self.drop_path_prob = drop_path_prob

#     def get_config(self):
#         config = super(SwinTransformerBlock, self).get_config()
#         config.update({   "dim" : self.dim,
#                           "num_patch" : self.num_patch,
#                           "num_heads" : self.num_heads,
#                           "window_size" : self.window_size,
#                           "shift_size" : self.shift_size,
#                           "num_mlp" : self.num_mlp,
#                           "qkv_bias" : self.qkv_bias,
#                           "qk_scale" : self.qk_scale,
#                           "mlp_drop" : self.mlp_drop,
#                           "attn_drop" : self.attn_drop,
#                           "proj_drop" : self.proj_drop,
#                           "drop_path_prob" : self.drop_path_prob})
#         return config

import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.layers import Dense, LayerNormalization # Import necessary Keras layers

# Giả định các lớp này đã được định nghĩa ở cấp cao nhất
# class PatchExtract(...): ...
# class PatchEmbedding(...): ...
# class PatchMerging(...): ...
# class PatchExpanding(...): ...
# class WindowAttention(...): ...
# class Mlp(...): ...
# class DropPath(...): ...

# Hàm padding (đặt bên ngoài lớp SwinTransformerBlock nếu nó là hàm tiện ích chung)
def pad_to_multiple(x, multiple):
    B, H, W, C = tf.shape(x)
    pad_H = (multiple - H % multiple) % multiple
    pad_W = (multiple - W % multiple) % multiple

    if pad_H > 0 or pad_W > 0:
        paddings = [[0, 0], [0, pad_H], [0, pad_W], [0, 0]]
        x = tf.pad(x, paddings, "CONSTANT") # Pad with zeros
    return x, pad_H, pad_W # Trả về cả lượng padding để xử lý sau này nếu cần

# Hàm window_partition (như đã sửa, nhưng bỏ raise ValueError nếu đã padding)
def window_partition(x, window_size):
    # Lấy hình dạng động để đảm bảo tính linh hoạt
    B, H, W, C = tf.shape(x)

    # Không cần kiểm tra divisibility ở đây nếu đã padding trước.
    # Nếu vẫn muốn kiểm tra, bạn có thể để lại nhưng đảm bảo padding đã được áp dụng.

    patch_num_H = H // window_size
    patch_num_W = W // window_size

    x = tf.reshape(x, shape=(B, patch_num_H, window_size, patch_num_W, window_size, C))
    x = tf.transpose(x, (0, 1, 3, 2, 4, 5))
    windows = tf.reshape(x, shape=(-1, window_size, window_size, C))

    return windows

# Hàm window_unpartition để nối lại các cửa sổ
def window_unpartition(windows, window_size, H, W, C):
    # Tính toán số lượng cửa sổ theo chiều cao và chiều rộng
    B_prime, _, _, _ = tf.shape(windows) # B_prime là (batch_size * num_windows)

    patch_num_H = H // window_size
    patch_num_W = W // window_size

    # Reshape ngược lại từ (Num_windows * Batch, window_size, window_size, C)
    x = tf.reshape(windows, shape=(-1, patch_num_H, patch_num_W, window_size, window_size, C))

    # Hoán vị ngược lại
    x = tf.transpose(x, (0, 1, 3, 2, 4, 5)) # (batch_size, num_windows_h, window_h, num_windows_w, window_w, C)

    # Reshape thành hình ảnh ban đầu
    x = tf.reshape(x, shape=(-1, H, W, C))
    return x


# Định nghĩa SwinTransformerBlock (phiên bản đã sửa)
class SwinTransformerBlock(layers.Layer):
    def __init__(self, dim, num_patch, num_heads, window_size=7, shift_size=0, num_mlp=1024,
                 qkv_bias=True, qk_scale=None, mlp_drop=0, attn_drop=0, proj_drop=0, drop_path_prob=0, name='', **kwargs):
        super().__init__(**kwargs)

        self.dim = dim # number of input dimensions
        self.num_patch = num_patch # number of embedded patches; a tuple of  (heigh, width)
        self.num_heads = num_heads # number of attention heads
        self.window_size = window_size # size of window
        self.shift_size = shift_size # size of window shift
        self.num_mlp = num_mlp # number of MLP nodes
        self.qkv_bias = qkv_bias
        self.qk_scale = qk_scale
        self.mlp_drop = mlp_drop
        self.attn_drop = attn_drop
        self.proj_drop = proj_drop
        self.drop_path_prob = drop_path_prob
        self.prefix = name

        if self.shift_size > self.window_size:
            raise ValueError("shift_size cannot be greater than window_size")

        self.norm1 = LayerNormalization(epsilon=1e-5, name='{}_norm1'.format(self.prefix))
        self.attn = WindowAttention(
            dim=self.dim,
            window_size=(self.window_size, self.window_size),
            num_heads=self.num_heads,
            qkv_bias=self.qkv_bias,
            qk_scale=self.qk_scale,
            attn_drop=self.attn_drop,
            proj_drop=self.proj_drop,
        )
        self.drop_path = drop_path(drop_path_prob)
        self.norm2 = LayerNormalization(epsilon=1e-5, name='{}_norm1'.format(self.prefix))

        self.mlp = Mlp([num_mlp, dim], drop=mlp_drop, name=self.prefix)
        # self.mlp = Mlp(
        #     in_features=self.dim,
        #     hidden_features=int(self.dim * self.mlp_ratio),
        #     out_features=self.dim,
        #     act_layer=tf.nn.gelu,
        #     drop=self.drop_rate
        # )

        # Build attention mask if shift_size > 0 (for shifted window attention)
        if self.shift_size > 0:
            # Mask generation logic (usually done once in build or __init__)
            # This part typically depends on the feature map resolution for this stage
            # and might need to be created dynamically based on input_shape in call
            # or pre-calculated for fixed resolutions.
            # For simplicity, we'll create it directly in call for now,
            # but in a real Swin implementation, it's often more optimized.
            self.build_mask_on_call = True
        else:
            self.build_mask_on_call = False

    def build(self, input_shape):
        # input_shape: (batch_size, num_patches, embed_dim)
        # Chúng ta cần H và W để tạo mask, sẽ lấy từ input_shape ở call
        super().build(input_shape)

    def call(self, x, training=False):
        B, L, C = tf.shape(x) # L = H * W
        H_in = W_in = tf.cast(tf.sqrt(tf.cast(L, tf.float32)), tf.int32) # Giả sử hình vuông

        shortcut = x
        x = self.norm1(x)

        # Reshape từ (B, L, C) về (B, H, W, C)
        x = tf.reshape(x, (B, H_in, W_in, C))

        # Áp dụng padding nếu cần
        x_padded, pad_H, pad_W = pad_to_multiple(x, self.window_size)
        H_padded, W_padded = tf.shape(x_padded)[1], tf.shape(x_padded)[2]

        # Nếu shift_size > 0, thực hiện cyclic shift
        if self.shift_size > 0:
            shifted_x = tf.roll(x_padded, shift=[-self.shift_size, -self.shift_size], axis=[1, 2])
            # Tạo attention mask nếu shift_size > 0
            img_mask = tf.zeros((1, H_padded, W_padded, 1))
            h_slices = (slice(0, -self.window_size),
                        slice(-self.window_size, -self.shift_size),
                        slice(-self.shift_size, None))
            w_slices = (slice(0, -self.window_size),
                        slice(-self.window_size, -self.shift_size),
                        slice(-self.shift_size, None))
            cnt = 0
            for h in h_slices:
                for w in w_slices:
                    img_mask = tf.tensor_scatter_nd_update(img_mask, [[0, h.start or 0, w.start or 0, 0]], [tf.cast(cnt, tf.float32)])
                    cnt += 1

            mask_windows = window_partition(img_mask, self.window_size)
            mask_windows = tf.reshape(mask_windows, [-1, self.window_size * self.window_size])
            attn_mask = tf.expand_dims(mask_windows, axis=1) - tf.expand_dims(mask_windows, axis=2)
            attn_mask = tf.where(attn_mask != 0, -100.0, 0.0) # Sử dụng -100.0 cho các khu vực bị mask
        else:
            shifted_x = x_padded
            attn_mask = None # Không có mask nếu shift_size = 0

        # Chia cửa sổ
        x_windows = window_partition(shifted_x, self.window_size)
        # Flatten cửa sổ
        x_windows = tf.reshape(x_windows, (-1, self.window_size * self.window_size, C))

        # Áp dụng Attention
        attn_windows = self.attn(x_windows, mask=attn_mask, training=training)

        # Nối lại các cửa sổ
        attn_windows = tf.reshape(attn_windows, (-1, self.window_size, self.window_size, C))
        shifted_x = window_unpartition(attn_windows, self.window_size, H_padded, W_padded, C)

        # Đảo ngược cyclic shift nếu có
        if self.shift_size > 0:
            x = tf.roll(shifted_x, shift=[self.shift_size, self.shift_size], axis=[1, 2])
        else:
            x = shifted_x

        # Bỏ padding nếu có
        if pad_H > 0 or pad_W > 0:
            x = x[:, :H_in, :W_in, :] # Cắt bỏ phần padding

        # Reshape về dạng chuỗi lại
        x = tf.reshape(x, (B, L, C))

        # Add shortcut và MLP
        x = shortcut + self.drop_path(x, training=training)
        x = x + self.drop_path(self.mlp(self.norm2(x)), training=training)
        return x

    def compute_output_shape(self, input_shape):
        return input_shape # Swin Transformer Block giữ nguyên hình dạng đầu vào

    def get_config(self):
        config = super(SwinTransformerBlock, self).get_config()
        config.update({   "dim" : self.dim,
                          "num_patch" : self.num_patch,
                          "num_heads" : self.num_heads,
                          "window_size" : self.window_size,
                          "shift_size" : self.shift_size,
                          "num_mlp" : self.num_mlp,
                          "qkv_bias" : self.qkv_bias,
                          "qk_scale" : self.qk_scale,
                          "mlp_drop" : self.mlp_drop,
                          "attn_drop" : self.attn_drop,
                          "proj_drop" : self.proj_drop,
                          "drop_path_prob" : self.drop_path_prob})
        return config



from tensorflow.keras.layers import Input, Dropout, Lambda, Conv2D, Conv2DTranspose, MaxPooling2D, Concatenate, Activation, Add, multiply, add, concatenate, LeakyReLU, ZeroPadding2D, UpSampling2D, BatchNormalization, Dense, AveragePooling2D
# from tensorflow.keras import Input
from tensorflow.keras.models import Model
import tensorflow.keras.layers as layers
import tensorflow as tf
from tensorflow.keras import backend as K

# Assuming transformer_layers module exists and contains the necessary functions
# If not, you'll need to define these classes/functions or provide their source.
# Example of what transformer_layers might look like (you'll need to fill this in):
class transformer_layers:
    class patch_extract(tf.keras.layers.Layer):
        def __init__(self, patch_size, **kwargs):
            super().__init__(**kwargs)
            self.patch_size = patch_size

        def call(self, images):
            batch_size = tf.shape(images)[0]
            patches = tf.image.extract_patches(
                images=images,
                sizes=[1, self.patch_size[0], self.patch_size[1], 1],
                strides=[1, self.patch_size[0], self.patch_size[1], 1],
                rates=[1, 1, 1, 1],
                padding='VALID',
            )
            patch_dims = patches.shape[-1]
            patches = tf.reshape(patches, [batch_size, -1, patch_dims])
            return patches

    class patch_embedding(tf.keras.layers.Layer):
        def __init__(self, num_patches, embed_dim, **kwargs):
            super().__init__(**kwargs)
            self.num_patches = num_patches
            self.embed_dim = embed_dim
            self.projection = Dense(embed_dim)

        def build(self, input_shape):
            # Positional embedding (learnable)
            self.position_embedding = self.add_weight(
                name="position_embedding",
                shape=(1, self.num_patches, self.embed_dim),
                initializer="random_normal",
                trainable=True,
            )
            super().build(input_shape)

        def call(self, patches):
            encoded = self.projection(patches) + self.position_embedding
            return encoded

    class patch_expanding(tf.keras.layers.Layer):
        def __init__(self, num_patch, embed_dim, upsample_rate=2, return_vector=True, **kwargs):
            super().__init__(**kwargs)
            self.num_patch = num_patch
            self.embed_dim = embed_dim
            self.upsample_rate = upsample_rate
            self.return_vector = return_vector
            # Note: self.linear_projection should output embed_dim // 2
            self.linear_projection = Dense(embed_dim // 2, use_bias=False, name=f"{self.name}_linear_proj")
            self.norm = LayerNormalization(epsilon=1e-5, name=f"{self.name}_norm")

        def build(self, input_shape):
            super().build(input_shape)

        def call(self, x):
            # Get static H and W from self.num_patch for the *current* resolution
            H, W = self.num_patch

            # Get dynamic batch size
            B = tf.shape(x)[0]
            # C is input channel, which should be self.embed_dim
            C_input = x.shape[-1] # This will be the C from the previous merged block, e.g., 2*embed_dim

            # Ensure the input length matches H*W
            assert x.shape[1] == H * W, f"Input feature has wrong number of tokens. Expected {H*W}, got {x.shape[1]}"

            # Apply linear projection first to reduce dimensions
            x = self.linear_projection(x) # Output shape: (B, H*W, embed_dim // 2)
            C_proj = self.embed_dim // 2 # Channel after projection

            x = tf.reshape(x, (B, H, W, C_proj)) # Reshape to 4D for resizing

            # Perform upsampling
            x = tf.image.resize(x, [H * self.upsample_rate, W * self.upsample_rate], method=tf.image.ResizeMethod.BILINEAR)

            if self.return_vector:
                new_H = H * self.upsample_rate
                new_W = W * self.upsample_rate
                x = tf.reshape(x, (B, new_H * new_W, C_proj)) # Reshape back to sequence

            x = self.norm(x)
            return x

        def compute_output_shape(self, input_shape):
            # input_shape: (batch_size, sequence_length, C_input)
            batch_size = input_shape[0]
            H, W = self.num_patch
            new_H = H * self.upsample_rate
            new_W = W * self.upsample_rate
            new_C = self.embed_dim // 2 # Output channel after linear_projection

            if self.return_vector:
                return (batch_size, new_H * new_W, new_C)
            else:
                return (batch_size, new_H, new_W, new_C)

        def get_config(self):
            config = super().get_config()
            config.update({
                'num_patch': self.num_patch,
                'embed_dim': self.embed_dim,
                'upsample_rate': self.upsample_rate,
                'return_vector': self.return_vector,
            })
            return config

import tensorflow as tf
from tensorflow.keras.layers import Dense, LayerNormalization

class patch_expanding(tf.keras.layers.Layer):
    def __init__(self, num_patch, embed_dim, upsample_rate=2, return_vector=True, **kwargs):
        super().__init__(**kwargs)
        self.num_patch = num_patch # This should be a tuple (H_current, W_current)
        self.embed_dim = embed_dim # This is the target embed_dim after expanding
        self.upsample_rate = upsample_rate
        self.return_vector = return_vector

        # Instantiate layers in __init__. They will be built on first call.
        # It's good practice to give them unique names if they are part of a larger model
        self.linear_projection = Dense(embed_dim // 2, use_bias=False, name=f"{self.name}_linear_proj")
        self.norm = LayerNormalization(epsilon=1e-5, name=f"{self.name}_norm")

    def build(self, input_shape):
        # The layers (Dense, LayerNormalization) will build themselves automatically
        # when their .call() method is first invoked.
        # No specific variable creation needed here unless you have custom weights.
        super().build(input_shape)

    def call(self, x):
        # H, W from self.num_patch are static Python integers
        H_current, W_current = self.num_patch

        # Get dynamic batch size and current channel dimension from the input tensor
        # C_input is the channel dimension *before* linear_projection
        B = tf.shape(x)[0]
        C_input = x.shape[-1] # This works for getting the static last dimension

        # Assertion for input length consistency (using static H, W from self.num_patch)
        assert x.shape[1] == H_current * W_current, \
               f"Input feature has wrong number of tokens. Expected {H_current*W_current}, got {x.shape[1]}"

        # Apply linear projection to reduce dimensions (e.g., from 4*C to C/2)
        # Output shape: (B, H_current * W_current, self.embed_dim // 2)
        x = self.linear_projection(x)

        # New channel dimension after projection
        C_proj = self.embed_dim // 2

        # Reshape from (B, L, C_proj) to (B, H_current, W_current, C_proj) for spatial operations
        x = tf.reshape(x, (B, H_current, W_current, C_proj))

        # Perform upsampling using tf.image.resize
        H_upsampled = H_current * self.upsample_rate
        W_upsampled = W_current * self.upsample_rate
        x = tf.image.resize(x, [H_upsampled, W_upsampled], method=tf.image.ResizeMethod.BILINEAR)

        # Reshape back to sequence if return_vector is True
        if self.return_vector:
            x = tf.reshape(x, (B, H_upsampled * W_upsampled, C_proj))

        x = self.norm(x)
        return x

    def compute_output_shape(self, input_shape):
        # input_shape will be (batch_size, L_input, C_input_channels_before_projection)
        batch_size = input_shape[0]

        H_current, W_current = self.num_patch # Static H, W at this stage

        H_upsampled = H_current * self.upsample_rate
        W_upsampled = W_current * self.upsample_rate

        C_output = self.embed_dim // 2 # Output channel dimension after projection

        if self.return_vector:
            return (batch_size, H_upsampled * W_upsampled, C_output)
        else:
            # If return_vector is False, the output is a 4D tensor (batch, H_upsampled, W_upsampled, C_output)
            return (batch_size, H_upsampled, W_upsampled, C_output)

    def get_config(self):
        config = super().get_config()
        config.update({
            'num_patch': self.num_patch,
            'embed_dim': self.embed_dim,
            'upsample_rate': self.upsample_rate,
            'return_vector': self.return_vector,
        })
        return config

class patch_merging(tf.keras.layers.Layer):
    '''
    Downsample embedded patches; it halfs the number of patches
    and double the embedded dimensions (c.f. pooling layers).

    Input
    ----------
        num_patch: number of patches to be embedded.
        embed_dim: number of embedded dimensions.

    Output
    ----------
        x: downsampled patches.

    '''
    def __init__(self, num_patch, embed_dim, name='', **kwargs):
        super().__init__(**kwargs)

        self.num_patch = num_patch
        self.embed_dim = embed_dim

        # A linear transform that doubles the channels
        self.linear_trans = Dense(2*embed_dim, use_bias=False, name='{}_linear_trans'.format(name))

    def call(self, x):

        H, W = self.num_patch
        B, L, C = x.get_shape().as_list()

        assert (L == H * W), 'input feature has wrong size'
        assert (H % 2 == 0 and W % 2 == 0), '{}-by-{} patches received, they are not even.'.format(H, W)

        # Convert the patch sequence to aligned patches
        x = tf.reshape(x, shape=(-1, H, W, C))

        # Downsample
        x0 = x[:, 0::2, 0::2, :]  # B H/2 W/2 C
        x1 = x[:, 1::2, 0::2, :]  # B H/2 W/2 C
        x2 = x[:, 0::2, 1::2, :]  # B H/2 W/2 C
        x3 = x[:, 1::2, 1::2, :]  # B H/2 W/2 C
        x = tf.concat((x0, x1, x2, x3), axis=-1)

        # Convert to the patch squence
        x = tf.reshape(x, shape=(-1, (H//2)*(W//2), 4*C))

        # Linear transform
        x = self.linear_trans(x)

        return x

    def get_config(self):
        config = super(patch_merging, self).get_config()
        config.update({"num_patch": self.num_patch, "embed_dim": self.embed_dim})
        return config


######################################################################################################################################
############### SWIN-Unet ############################################################################################################
######################################################################################################################################

def swin_transformer_stack(X, stack_num, embed_dim, num_patch, num_heads, window_size, num_mlp, shift_window=True, name='', mlp_drop_rate = 0, attn_drop_rate = 0, proj_drop_rate = 0, drop_path_rate = 0):
    '''
    Stacked Swin Transformers that share the same token size.

    Alternated Window-MSA and Swin-MSA will be configured if `shift_window=True`, Window-MSA only otherwise.
    *Dropout is turned off.
    '''
    # Turn-off dropouts
      # Droupout after each MLP layer
      # Dropout after Swin-Attention
      # Dropout at the end of each Swin-Attention block, i.e., after linear projections
      # Drop-path within skip-connections

    qkv_bias = True # Convert embedded patches to query, key, and values with a learnable additive value
    qk_scale = None # None: Re-scale query based on embed dimensions per attention head # Float for user specified scaling factor

    if shift_window:
        shift_size = window_size // 2
    else:
        shift_size = 0

    for i in range(stack_num):

        if i % 2 == 0:
            shift_size_temp = 0
        else:
            shift_size_temp = shift_size

        X = SwinTransformerBlock(dim=embed_dim,
                                     num_patch=num_patch,
                                     num_heads=num_heads,
                                     window_size=window_size,
                                     shift_size=shift_size_temp,
                                     num_mlp=num_mlp,
                                     qkv_bias=qkv_bias,
                                     qk_scale=qk_scale,
                                     mlp_drop=mlp_drop_rate,
                                     attn_drop=attn_drop_rate,
                                     proj_drop=proj_drop_rate,
                                     drop_path_prob=drop_path_rate,
                                     name='name{}'.format(i))(X)
    return X


def swin_unet_2d_base(input_tensor, filter_num_begin, depth, stack_num_down, stack_num_up,
                      patch_size, num_heads, window_size, num_mlp, shift_window=True, name='swin_unet', mlp_drop_rate = 0, attn_drop_rate = 0, proj_drop_rate = 0, drop_path_rate = 0):
    '''
    The base of Swin-UNET.

    The general structure:

    1. Input image --> a sequence of patches --> tokenize these patches
    2. Downsampling: swin-transformer --> patch merging (pooling)
    3. Upsampling: concatenate --> swin-transfprmer --> patch expanding (unpooling)
    4. Model head

    '''
    print(f"Kiểu của input_tensor tại đây: {type(input_tensor)}")
    print(f"Giá trị của input_tensor tại đây: {input_tensor}")
    # Compute number be patches to be embeded
    # Lấy kích thước tĩnh của tensor đầu vào.
    # K.int_shape() sẽ trả về một tuple Python, ví dụ: (None, 192, 256, 3)
    input_shape_tuple = K.int_shape(input_tensor)

    # Chiều đầu tiên (input_shape_tuple[0]) là batch_size, thường là None.
    # Chiều thứ hai (input_shape_tuple[1]) là chiều cao của ảnh.
    # Chiều thứ ba (input_shape_tuple[2]) là chiều rộng của ảnh.
    img_height = input_shape_tuple[1]
    img_width = input_shape_tuple[2]

    num_patch_x = img_height // patch_size[0]
    num_patch_y = img_width // patch_size[1]

    # Number of Embedded dimensions
    embed_dim = filter_num_begin

    depth_ = depth

    X_skip = []

    X = input_tensor

    # Patch extraction
    X = transformer_layers.patch_extract(patch_size)(X)

    # Embed patches to tokens
    X = transformer_layers.patch_embedding(num_patch_x*num_patch_y, embed_dim)(X)

    # The first Swin Transformer stack
    X = swin_transformer_stack(X,
                                 stack_num=stack_num_down,
                                 embed_dim=embed_dim,
                                 num_patch=(num_patch_x, num_patch_y),
                                 num_heads=num_heads[0],
                                 window_size=window_size[0],
                                 num_mlp=num_mlp,
                                 shift_window=shift_window,
                                 name='{}_swin_down0'.format(name),
                                 mlp_drop_rate = mlp_drop_rate,
                                 attn_drop_rate = attn_drop_rate,
                                 proj_drop_rate = proj_drop_rate,
                                 drop_path_rate = drop_path_rate)
    X_skip.append(X)

    # Downsampling blocks
    for i in range(depth_-1):

        # Patch merging
        X = patch_merging((num_patch_x, num_patch_y), embed_dim=embed_dim, name='down{}'.format(i))(X)

        # update token shape info
        embed_dim = embed_dim*2
        num_patch_x = num_patch_x//2
        num_patch_y = num_patch_y//2

        # Swin Transformer stacks
        X = swin_transformer_stack(X,
                                     stack_num=stack_num_down,
                                     embed_dim=embed_dim,
                                     num_patch=(num_patch_x, num_patch_y),
                                     num_heads=num_heads[i+1],
                                     window_size=window_size[i+1],
                                     num_mlp=num_mlp,
                                     shift_window=shift_window,
                                     name='{}_swin_down{}'.format(name, i+1),
                                     mlp_drop_rate = mlp_drop_rate,
                                     attn_drop_rate = attn_drop_rate,
                                     proj_drop_rate = proj_drop_rate,
                                     drop_path_rate = drop_path_rate)

        # Store tensors for concat
        X_skip.append(X)

    # reverse indexing encoded tensors and hyperparams
    X_skip = X_skip[::-1]
    num_heads = num_heads[::-1]
    window_size = window_size[::-1]

    # upsampling begins at the deepest available tensor
    X = X_skip[0]

    # other tensors are preserved for concatenation
    X_decode = X_skip[1:]

    depth_decode = len(X_decode)

    for i in range(depth_decode):

        # Patch expanding
        X = transformer_layers.patch_expanding(num_patch=(num_patch_x, num_patch_y),
                                                 embed_dim=embed_dim,
                                                 upsample_rate=2,
                                                 return_vector=True, name='{}_patch_expanding_{}'.format(name, i))(X)


        # update token shape info
        embed_dim = embed_dim//2
        num_patch_x = num_patch_x*2
        num_patch_y = num_patch_y*2

        # Concatenation and linear projection
        X = concatenate([X, X_decode[i]], axis=-1, name='{}_concat_{}'.format(name, i))
        X = Dense(embed_dim, use_bias=False, name='{}_concat_linear_proj_{}'.format(name, i))(X)

        # Swin Transformer stacks
        X = swin_transformer_stack(X,
                                     stack_num=stack_num_up,
                                     embed_dim=embed_dim,
                                     num_patch=(num_patch_x, num_patch_y),
                                     num_heads=num_heads[i],
                                     window_size=window_size[i],
                                     num_mlp=num_mlp,
                                     shift_window=shift_window,
                                     name='{}_swin_up{}'.format(name, i),
                                     mlp_drop_rate = mlp_drop_rate,
                                     attn_drop_rate = attn_drop_rate,
                                     proj_drop_rate = proj_drop_rate,
                                     drop_path_rate = drop_path_rate)

    # The last expanding layer; it produces full-size feature maps based on the patch size
    # !!! <--- "patch_size[0]" is used; it assumes patch_size = (size, size)

    X = transformer_layers.patch_expanding(num_patch=(num_patch_x, num_patch_y),
                                             embed_dim=embed_dim,
                                             upsample_rate=patch_size[0],
                                             return_vector=False, name='patch_expanding_last')(X)

    return X

def Swin_unet(
    input_size = (1024, 1024, 1),
    filter_num_begin = 128,      # number of channels in the first downsampling block; it is also the number of embedded dimensions
    depth = 4,                   # the depth of SwinUNET; depth=4 means three down/upsampling levels and a bottom level
    stack_num_down = 2,          # number of Swin Transformers per downsampling level
    stack_num_up = 2,            # number of Swin Transformers per upsampling level
    patch_size = 8,        # Extract 4-by-4 patches from the input image. Height and width of the patch must be equal.
    att_heads = 4,   # number of attention heads per down/upsampling level
    w_size = 4, # the size of attention window per down/upsampling level
    mlp_ratio = 4, # Ratio of mlp hidden dim to embedding dim. Default: 4
    shift_window=True,           # Apply window shifting, i.e., Swin-MSA,
    input_centering=True,
    dropout = 0.1
    ):

    num_mlp = mlp_ratio*filter_num_begin         # number of MLP nodes within the Transformer

    num_heads =   [2**i*att_heads for i in range(depth)] # number of attention heads per down/upsampling level
    window_size = [w_size for _ in range(depth)]


    mlp_drop_rate = dropout
    attn_drop_rate = dropout
    proj_drop_rate = dropout
    drop_path_rate = dropout

    IN = Input(input_size)

    if input_centering:
        # Create a Lambda layer to replace 0.5 with -1
        replace_half_with_negative_one = tf.keras.layers.Lambda(
            lambda x: tf.where(tf.equal(x, 0.5), tf.constant(-1.0, dtype=x.dtype), x)
        )

        IN = replace_half_with_negative_one(IN)
    else:
        pass


    # Base architecture
    X = swin_unet_2d_base(IN, filter_num_begin, depth, stack_num_down, stack_num_up,
                          (patch_size,patch_size), num_heads, window_size, num_mlp,
                          shift_window=shift_window, name='swin_unet',
                          mlp_drop_rate = mlp_drop_rate,
                        attn_drop_rate = attn_drop_rate,
                        proj_drop_rate = proj_drop_rate,
                        drop_path_rate = drop_path_rate)
    # Output section
    OUT = Conv2D(1, kernel_size=1, use_bias=False, activation='relu')(X)

    # Model configuration
    model = Model(inputs=[IN,], outputs=[OUT,])

    return model

model = Swin_unet(input_size=(192, 256, 3))
model.summary()

!pip install visualkeras

import visualkeras
visualkeras.layered_view(model, legend=True)

"""## CASPIAN_beta"""

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, Concatenate, LeakyReLU, BatchNormalization, MaxPool2D, ReLU, Activation, MaxPooling2D, AveragePooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D, Add
from tensorflow.keras.initializers import RandomNormal, HeNormal, VarianceScaling, HeUniform, GlorotUniform, GlorotNormal

def CASPIAN_beta(input_shape=(192, 256, 3), filters=256, cardinality=36, activation='tanh', init="glorot_normal",
                    input_centering=True, depth=4, bottleneck_depth=8, compression_factor=0.9, gr_level=4, sup_level=1, version=1):

    # Map init string to actual initializer
    if init == "glorot_normal":
        kernel_initializer_val = GlorotNormal()
    else:
        # Default or handle other string initializers
        kernel_initializer_val = init

    if version == 4:
        bottleneck_depth = 2

    input_grid = layers.Input(shape=input_shape)

    if input_centering:
        # Create a Lambda layer to replace 0.5 with -1
        replace_half_with_negative_one = layers.Lambda(
            lambda x_in: tf.where(tf.equal(x_in, 0.5), tf.constant(-1.0, dtype=x_in.dtype), x_in)
        )
        x = replace_half_with_negative_one(input_grid)
    else:
        x = input_grid

    # Encoder
    pools = []
    for i in range(depth):
        if i == 0:
            #Entry block
            pool_size=2
            s = layers.Conv2D(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=kernel_initializer_val)(x)
            if version != 3:
                #Stratified Pooling
                if input_centering:
                    # Explicitly pass x to lambda functions
                    mask_neg_one = layers.Lambda(
                        lambda x_in: tf.where(tf.equal(x_in, -1.0), x_in, tf.zeros_like(x_in))
                    )(x)
                    mask_pos_one = layers.Lambda(
                        lambda x_in: tf.where(tf.equal(x_in, 1.0), x_in, tf.zeros_like(x_in))
                    )(x)
                else:
                    mask_half = layers.Lambda(
                        lambda x_in: tf.where(tf.equal(x_in, 0.5), x_in, tf.zeros_like(x_in))
                    )(x)
                    mask_pos_one = layers.Lambda(
                        lambda x_in: tf.where(tf.equal(x_in, 1.0), x_in, tf.zeros_like(x_in))
                    )(x)

                if input_centering:
                    p = layers.concatenate([mask_neg_one, mask_pos_one], axis=-1)
                else:
                    p = layers.concatenate([mask_half, mask_pos_one], axis=-1)

                p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(p)
                pools.append(p)
                x = layers.concatenate([s, p], axis=-1)
            else:
                x = s
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=kernel_initializer_val)(x)
            x = layers.add([s, x])
            x = layers.Activation(activation)(x)
        else:
            # Downsampling block with Depthwise convs.
            s = x
            d = layers.DepthwiseConv2D(depth_multiplier=1, kernel_size=(2, 2), strides=(2, 2), padding="same", activation=activation, depthwise_initializer=kernel_initializer_val)(x)
            if version != 3:
                p = layers.AveragePooling2D(pool_size=(pool_size, pool_size), strides=(2, 2), padding='same')(pools[-1])
                pools.append(p)
                x = layers.concatenate([d, p], axis=-1)
            else:
                x = d
            x = layers.Conv2D(filters, (1, 1), padding="same", activation=None, kernel_initializer=kernel_initializer_val)(x)
            b = layers.Conv2D(filters, (1, 1), strides=(2, 2), padding="same", activation=None, kernel_initializer=kernel_initializer_val)(s)
            x = layers.add([b, x])
            x = layers.Activation(activation)(x)

    # Information Bottleneck layer
    for _ in range(bottleneck_depth):
        x = resnetxt_block(x, filters=filters, cardinality=cardinality, init=kernel_initializer_val, activation=activation)

    # Decoder
    the_weights = None
    for i in range(depth - 1, -1, -1):
        # Pooling Supervised Upsampling block
        if version != 3:
            x = layers.Concatenate(axis=-1)([x, pools[i]])
        x = layers.Conv2DTranspose(filters=filters, kernel_size=(2, 2), strides=(2, 2), padding='same', activation=activation, kernel_initializer=kernel_initializer_val)(x)
        # Channel weights
        if version != 2 and version != 3:
            if sup_level != 0:
                # FIX: Wrap tf.reduce_sum in a Lambda layer
                p_sum = layers.Lambda(lambda t: tf.reduce_sum(t, axis=-1, keepdims=True))(pools[i])
                p = layers.AveragePooling2D(pool_size=(gr_level, gr_level), strides=(gr_level, gr_level), padding='same')(p_sum)
                #p = tf.reduce_sum(p, axis=-1, keepdims=True) # This line was commented out, so no change needed.
                spatial_encoding_flattened = layers.Flatten()(p)
                weights = layers.Dense(int(compression_factor * filters), activation=activation, kernel_initializer=kernel_initializer_val)(spatial_encoding_flattened)
                weights = layers.Dense(filters, activation='sigmoid', kernel_initializer=kernel_initializer_val)(weights)
                weights_reshaped = layers.Reshape((1, 1, filters))(weights)
                the_weights = weights_reshaped
                sup_level = sup_level - 1
            else:
                weights_reshaped = the_weights
            unifying_convs = layers.Conv2D(filters, (1, 1), padding='same', kernel_initializer=kernel_initializer_val, activation=activation)(x)
            x = layers.Multiply()([unifying_convs, weights_reshaped])
        else:
            x = layers.Conv2D(filters, (1, 1), padding='same', kernel_initializer=kernel_initializer_val, activation=activation)(x)

    # Output head
    out = layers.Conv2D(1, kernel_size=(1, 1), strides=(1, 1), activation=None, padding='same', kernel_initializer=kernel_initializer_val)(x)

    if version != 1:
        # FIX: Wrap tf.reduce_sum in a Lambda layer
        summed_features = layers.Lambda(lambda t: tf.reduce_sum(t, axis=-1, keepdims=True))(x)
        out = layers.add([summed_features, out])

    out = layers.Activation('relu')(out)

    model = tf.keras.models.Model(inputs=input_grid, outputs=out)

    return model

model = CASPIAN_beta(input_shape=(192, 256, 3))
model.summary()

"""# PAPER 4: [Dense-U-net: Dense encoder–decoder network for holographic imaging of 3D particle fields. In Optics Communications Volume 493, 15 August 2021, 126970](https://github.com/THUHoloLab/Dense-U-net)

## Dense Unet
"""

import tensorflow as tf
from tensorflow.keras.layers import BatchNormalization, Activation, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Input, concatenate, LeakyReLU
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import l2
import keras.backend as K # Still using K.image_data_format for channel axis
from tensorflow.keras.initializers import HeNormal

def Conv_Block(input_tensor, filters, bottleneck=False, weight_decay=1e-4):
    """    封装卷积层

    :param input_tensor: 输入张量
    :param filters: 卷积核数目
    :param bottleneck: 是否使用bottleneck
    :param dropout_rate: dropout比率
    :param weight_decay: 权重衰减率
    :return:
    """
    concat_axis = 1 if K.image_data_format() == 'channel_first' else -1  # 确定格式

    x = BatchNormalization(axis=concat_axis, epsilon=1.1e-5)(input_tensor)
    x = Activation('relu')(x)

    # if bottleneck:
    #     # 使用bottleneck进行降维
    #     inter_channel = filters
    #     x = Conv2D(inter_channel, (1, 1),
    #                kernel_initializer='he_normal',
    #                padding='same', use_bias=False,
    #                kernel_regularizer=l2(weight_decay))(x)
    #     x = BatchNormalization(axis=concat_axis, epsilon=1.1e-5)(x)
    #     x = Activation('relu')(x)

    x = Conv2D(filters, (3, 3), kernel_initializer=HeNormal(), padding='same', use_bias=False)(x)

    return x
def dens_block(input_tensor, nb_filter):
    x1 = Conv_Block(input_tensor,nb_filter)
    add1 = concatenate([x1, input_tensor], axis=-1)
    x2 = Conv_Block(add1,nb_filter)
    add2 = concatenate([x1, input_tensor,x2], axis=-1)
    x3 = Conv_Block(add2,nb_filter)
    return x3

from keras.regularizers import l2

#model definition
def unet(input_shape=(512, 512, 3)):

    inputs = Input(input_shape)
    # x  = Conv2D(32, 1, strides=1, activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
    x = Conv2D(32, 7, kernel_initializer=HeNormal(), padding='same', strides=1,use_bias=False, kernel_regularizer=l2(1e-4))(inputs)
    #down first
    down1 = dens_block(x,nb_filter=64)
    pool1 = MaxPooling2D(pool_size=(2, 2))(down1)#256
    #down second
    down2 = dens_block(pool1,nb_filter=64)
    pool2 = MaxPooling2D(pool_size=(2, 2))(down2)#128
    #down third
    down3 = dens_block(pool2,nb_filter=128)
    pool3 = MaxPooling2D(pool_size=(2, 2))(down3)#64
    #down four
    down4 = dens_block(pool3,nb_filter=256)
    pool4 = MaxPooling2D(pool_size=(2, 2))(down4)#32
    #center
    conv5 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer=HeNormal())(pool4)
    conv5 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer=HeNormal())(conv5)
    drop5 = Dropout(0.5)(conv5)

    # up first
    up6 = UpSampling2D(size=(2, 2))(drop5)
    # up6 = UpSampling2D(size=(2, 2))(drop5)
    add6 = concatenate([down4, up6], axis=3)
    up6 = dens_block(add6,nb_filter=256)
    # up second
    up7 = UpSampling2D(size=(2, 2))(up6)
    #up7 = UpSampling2D(size=(2, 2))(conv6)
    add7 = concatenate([down3, up7], axis=3)
    up7 = dens_block(add7,nb_filter=128)
    # up third
    up8 = UpSampling2D(size=(2, 2))(up7)
    #up8 = UpSampling2D(size=(2, 2))(conv7)
    add8 = concatenate([down2, up8], axis=-1)
    up8 = dens_block(add8,nb_filter=64)
    #up four
    up9 =UpSampling2D(size=(2, 2))(up8)
    add9 = concatenate([down1, up9], axis=-1)
    up9 = dens_block(add9,nb_filter=64)
    # output
    conv10 = Conv2D(32, 7, strides=1, activation='relu', padding='same', kernel_initializer=HeNormal())(up9)
    conv10 = Conv2D(1, 1, activation='sigmoid')(conv10)
    model = Model(inputs=inputs, outputs=conv10)
    return model

model = unet((192, 256, 3))
model.summary()

# !pip install visualkeras

import visualkeras
visualkeras.layered_view(model, legend=True)

tf.keras.utils.plot_model(
    model,
    show_shapes=False,
    show_dtype=True,
    show_layer_names=False,
    rankdir='LR',
    expand_nested=True,
    dpi=50,
    show_layer_activations=True,
    show_trainable=False)

# !pip install visualkeras

import visualkeras
visualkeras.layered_view(unet, legend=True)

"""# PAPER 5: [Enhanced Encoder-Decoder Architecture for Accurate Monocular Depth Estimation. In arXiv [2410.11610] ](https://github.com/dabbrata/Depth-Estimation-Enc-Dec)"""

from tensorflow.keras.layers import Input, concatenate, LeakyReLU, BatchNormalization, Conv2D, MaxPooling2D, AveragePooling2D, Dropout, UpSampling2D, ZeroPadding2D
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from skimage.transform import resize
import os
import csv
import PIL
import numpy as np
import random
import cv2
import imutils
import tensorflow.keras.backend as K
import tensorflow as tf
from tensorflow.keras.applications import InceptionResNetV2

def downsampling_block(input_tensor, n_filters):
  x = Conv2D(filters=n_filters, kernel_size=(3,3), padding='same')(input_tensor)
  x = LeakyReLU(negative_slope=0.2)(x)
  x = BatchNormalization()(x)

  x = Conv2D(filters=n_filters, kernel_size=(3,3), padding='same')(x)
  x = LeakyReLU(negative_slope=0.2)(x)
  x = BatchNormalization()(x)
  return x

def upsampling_block(input_tensor, n_filters, name, concat_with):
  x = UpSampling2D((2, 2), interpolation='bilinear', name=name)(input_tensor)
  x = Conv2D(filters=n_filters, kernel_size=(3, 3), padding='same', name=name+"_convA")(x)
  x = LeakyReLU(negative_slope=0.2)(x)

  x = concatenate([x, concat_with], axis=3)

  x = Conv2D(filters=n_filters, kernel_size=(3, 3), padding='same', name=name+"_convB")(x)
  x = LeakyReLU(negative_slope=0.2)(x)
  x = BatchNormalization()(x)

  x = Conv2D(filters=n_filters, kernel_size=(3, 3), padding='same', name=name+"_convC")(x)
  x = LeakyReLU(negative_slope=0.2)(x)
  x = BatchNormalization()(x)
  return x

def build(height, width, depth):
  # input
  i = tf.keras.Input(shape=(height, width, depth), name= 'input_layer_0')

  iresnet = InceptionResNetV2(include_top = False, weights = None, input_tensor = i)
  iresnet.summary()

  # encoder

  conv1 = iresnet.get_layer("input_layer_0").output
  pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
  conv2 = iresnet.get_layer("activation").output
  conv2 = ZeroPadding2D(((1,0),(1,0)))(conv2)
  pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
  conv3 = iresnet.get_layer("activation_3").output
  conv3 = ZeroPadding2D((1,1))(conv3)
  pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
  conv4 = iresnet.get_layer("activation_74").output
  conv4 = ZeroPadding2D(((2,1),(2,1)))(conv4)
  pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)

  # bottleneck
  conv5 = iresnet.get_layer("activation_161").output
  conv5 = ZeroPadding2D((1,1))(conv5)
  conv5 = LeakyReLU(negative_slope=0.2)(conv5)


  # decoder
  conv6 = upsampling_block(conv5, 256, "up1", concat_with=conv4)
  conv7 = upsampling_block(conv6, 128, "up2", concat_with=conv3)
  conv8 = upsampling_block(conv7, 64, "up3", concat_with=conv2)
  conv9 = upsampling_block(conv8, 32, "up4", concat_with=conv1)

  # output
  o = Conv2D(filters=1, kernel_size=3, strides=(1,1), activation='sigmoid', padding='same', name='conv10')(conv9)

  model = Model(inputs=i, outputs=o)
  return model

HEIGHT, WIDTH = 192, 256
model = build(HEIGHT, WIDTH, 3)

model.summary()

"""# MODEL U_NET"""

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, Concatenate, LeakyReLU, BatchNormalization, MaxPool2D, ReLU, Activation, MaxPooling2D, AveragePooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D, Add
from tensorflow.keras.initializers import RandomNormal, HeNormal, VarianceScaling, HeUniform, GlorotUniform
import numpy as np

def downscale_block(input_tensor, filters, kernel_size=(3, 3), padding="same", strides=1, max_pool=False):

    if not max_pool:
        conv0 = Conv2D(
            filters=filters * 2,
            kernel_size=np.array(kernel_size) * 2 + 1,
            strides=strides,
            padding=padding,
            activation='relu',
            kernel_initializer=HeUniform(seed=42),
            kernel_regularizer = tf.keras.regularizers.L2(0.0001),
            activity_regularizer=tf.keras.regularizers.L2(0.0001),
            bias_regularizer=tf.keras.regularizers.L2(0.0001))
        pool = AveragePooling2D((2, 2), strides=(2, 2), padding='same')
    else:
        pool = MaxPool2D((2, 2), strides=(2, 2), padding='same')

    convA = Conv2D(
        filters= filters,
        kernel_size=np.array(kernel_size),
        strides=strides,
        padding=padding,
        activation='relu',
        kernel_initializer=HeUniform(seed=42),
        kernel_regularizer = tf.keras.regularizers.L2(0.0001),
        activity_regularizer=tf.keras.regularizers.L2(0.0001),
        bias_regularizer=tf.keras.regularizers.L2(0.0001))

    convB = Conv2D(
        filters,
        np.array(kernel_size),
        strides,
        padding,
        activation='relu',
        kernel_initializer=HeUniform(seed=42),
        kernel_regularizer = tf.keras.regularizers.L2(0.0001),
        activity_regularizer=tf.keras.regularizers.L2(0.0001),
        bias_regularizer=tf.keras.regularizers.L2(0.0001))


    reluA = LeakyReLU(negative_slope=0.3)
    reluB = LeakyReLU(negative_slope=0.3)
    reluC = LeakyReLU(negative_slope=0.3)
    bn2a = BatchNormalization(momentum=0.1, epsilon=1e-05)
    bn2b = BatchNormalization(momentum=0.1, epsilon=1e-05)
    bn2c = BatchNormalization(momentum=0.1, epsilon=1e-05)

    if not max_pool:
        d = conv0(input_tensor)
        x = bn2a(d)
        x = reluA(x)

        skip = Add()([x, d])

        p = pool(skip)

        return d, p
    else:
        d = convA(input_tensor)
        x = bn2a(d)
        x = reluA(x)

        x = convB(x)
        x = bn2b(x)
        x = reluB(x)

        x += d

        p = pool(x)

        return x, p

def upscale_block(input_tensor, skip, filters, kernel_size=(3, 3), padding="same", strides=1):
    us = UpSampling2D((2, 2))

    convA = Conv2D(
        filters,
        np.array(kernel_size),
        strides,
        padding,
        activation='relu',
        kernel_initializer=HeUniform(seed=42),
        kernel_regularizer = tf.keras.regularizers.L2(0.0001),
        activity_regularizer=tf.keras.regularizers.L2(0.0001),
        bias_regularizer=tf.keras.regularizers.L2(0.0001))

    convB = Conv2D(
        filters,
        np.array(kernel_size),
        strides,
        padding,
        activation='relu',
        kernel_initializer=HeUniform(seed=42),
        kernel_regularizer = tf.keras.regularizers.L2(0.0001),
        activity_regularizer=tf.keras.regularizers.L2(0.0001),
        bias_regularizer=tf.keras.regularizers.L2(0.0001))

    reluA = LeakyReLU(negative_slope=0.3)
    reluB = LeakyReLU(negative_slope=0.3)
    reluC = LeakyReLU(negative_slope=0.3)
    bn2a = BatchNormalization(momentum=0.1, epsilon=1e-05)
    bn2b = BatchNormalization(momentum=0.1, epsilon=1e-05)
    bn2c = BatchNormalization(momentum=0.1, epsilon=1e-05)
    conc = Concatenate(axis=-1)
    cond = Concatenate(axis=-1)

    x = us(input_tensor)

    d = convA(x)
    x = bn2a(d)
    x = reluA(x)

    x = convB(x)
    x = bn2b(x)
    x = reluB(x)
    x += d

    return x

def depth_estimation_model(input_tensor):

    """Mô hình ước tính độ sau"""

    bn_out = BatchNormalization(momentum=0.1, epsilon=1e-05)
    relu_out = LeakyReLU(negative_slope=0.1)

    filters = 32

    f = [filters, filters*2, filters*4, filters*8, filters*16, filters*32]
    # f = [64, 128, 256, 512, 1024]

    c1, p1 = downscale_block(input_tensor, f[0], max_pool=False)

    c2, p2 = downscale_block(p1, f[1], max_pool=True)

    c3, p3 = downscale_block(p2, f[2], max_pool=True)

    c4, p4 = downscale_block(p3, f[3], max_pool=True)

    middle, _ = downscale_block(p4, f[4], max_pool=True)

    u2 = upscale_block(middle, c4, f[3])
    u3 = upscale_block(u2, c3, f[2])
    u4 = upscale_block(u3, c2, f[1])
    u5 = upscale_block(u4, c1, f[0])

    output_tensor = bn_out(u5)
    output_tensor = relu_out(output_tensor)

    output_tensor = Conv2D(1,
                           (1, 1)
                           , padding="same"
                           , activation="sigmoid"
                           , kernel_initializer=VarianceScaling(scale=1.0, mode='fan_avg', distribution='uniform')
                           , kernel_regularizer=tf.keras.regularizers.L2(0.0001) )(output_tensor)

    return output_tensor

input_tensor = tf.keras.layers.Input(shape=(width, height, 3))
output_tensor = depth_estimation_model(input_tensor)
model = tf.keras.models.Model(inputs=input_tensor, outputs=output_tensor, name='DE')

print(model.count_params())
print(len(model.layers))
# tf.keras.utils.plot_model(
#     model,
#     show_shapes=False,
#     show_dtype=True,
#     show_layer_names=True,
#     rankdir='TB',
#     expand_nested=True,
#     dpi=100,
#     show_layer_activations=True,
#     show_trainable=True)

"""# VISUALIZATION MODEL SHAPE"""

!pip install visualkeras

import visualkeras
visualkeras.layered_view(model, legend=True)

"""# TRAIN CUSTOM"""

import tensorflow as tf

# Giả sử y_true và y_pred có shape (batch_size, height, width, 1)
# và giá trị pixel nằm trong khoảng [0, 1]
def ssim_loss(y_true, y_pred):
  # max_val là giá trị pixel tối đa, thường là 1.0 nếu ảnh đã được chuẩn hóa
  ssim_val = tf.image.ssim(y_true, y_pred, max_val=1.0)
  # SSIM càng cao (gần 1) thì loss càng thấp (gần 0)
  return 1.0 - tf.reduce_mean(ssim_val)

# Sau đó bạn có thể gán:
# Hoặc định nghĩa combined_loss nếu muốn kết hợp nhiều loss:
def combined_loss(y_true, y_pred):
    loss1 = ssim_loss(y_true, y_pred)
    loss2 = tf.reduce_mean(tf.square(y_true - y_pred))
    alpha = 0.8 # Trọng số cho SSIM loss
    return alpha * loss1 + (1 - alpha) * loss2

loss_fn = combined_loss # Gán hàm combined_loss cho loss_fn để sử dụng trong các step

# =====================================================================================================
import numpy as np
import matplotlib.pyplot as plt

THRESSHOD = 0.02
THRESSHOD_VAL = 0.02

def ssim_loss(y_true, y_pred):
  ssim_val = tf.image.ssim(y_true, y_pred, max_val=1.0)
  return 1.0 - tf.reduce_mean(ssim_val)

# Mean Absolute Error (MAE)
@tf.function
def calculate_mae(y_true, y_pred):
    return tf.reduce_mean(tf.abs(y_true - y_pred))

# Ví dụ: Định nghĩa Mean Square Error (MSE)
@tf.function
def calculate_mse(y_true, y_pred):
    return tf.reduce_mean(tf.square(y_true - y_pred))

# Ví dụ: Định nghĩa Root Mean Squared Error (RMSE)
@tf.function
def calculate_rmse(y_true, y_pred):
    return tf.sqrt(tf.reduce_mean(tf.square(y_true - y_pred)))

def combined_loss(y_true, y_pred):
    loss1 = ssim_loss(y_true, y_pred)
    loss2 = tf.reduce_mean(tf.square(y_true - y_pred))
    alpha = 0.8 # Trọng số cho SSIM loss
    return alpha * loss1 + (1 - alpha) * loss2

@tf.function
def train_step_tf(model, X, y, loss_fn, optimizer):
    with tf.GradientTape() as tape:
        y_pred = model(X, training=True)
        loss = loss_fn(y, y_pred) # Sử dụng loss_fn đã định nghĩa

    gradients = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))

    # dynamic threshold per batch
    max_truth = tf.reduce_max(y)
    threshold = THRESSHOD * max_truth
    acc = tf.reduce_mean(tf.cast(tf.abs(y - y_pred) < threshold, tf.float32))
    mae = calculate_mae(y, y_pred) # Tính MAE
    rmse = calculate_rmse(y, y_pred) # Tính RMSE
    mse = calculate_mse(y, y_pred) # Tính RMSE
    return loss, acc, mae, rmse, mse # Trả về các metrics mới

@tf.function
def validate_step_tf(model, X, y, loss_fn):
    y_pred = model(X, training=False)
    loss = loss_fn(y, y_pred) # Sử dụng loss_fn đã định nghĩa

    max_truth = tf.reduce_max(y)
    threshold = THRESSHOD_VAL * max_truth
    acc = tf.reduce_mean(tf.cast(tf.abs(y - y_pred) < threshold, tf.float32))
    mae = calculate_mae(y, y_pred) # Tính MAE
    rmse = calculate_rmse(y, y_pred) # Tính RMSE
    mse = calculate_mse(y, y_pred)
    return loss, acc, mae, rmse, mse # Trả về các metrics mới

import matplotlib.pyplot as plt

def plot_training_history(history):

    # Xác định số epoch dựa trên độ dài của một trong các list metrics
    epochs = range(1, len(history['train_loss']) + 1)

    # Tạo một figure với lưới 2x2 subplot
    plt.figure(figsize=(14, 6)) # Tăng kích thước để vừa 4 đồ thị

    # --- Đồ thị Loss ---
    plt.subplot(121)
    plt.plot(epochs, history['train_loss'], label='Mất mát (Train)', linestyle='-', marker='o', markersize=4)
    plt.plot(epochs, history['val_loss'], label='Mất mát (Validation)', linestyle='-', marker='x', markersize=4)
    plt.title('Hàm mất mát (Loss)')
    plt.xlabel('Epoch')
    plt.ylabel('Mất mát')
    plt.legend()
    plt.grid(True)

    # --- Đồ thị Accuracy ---
    plt.subplot(122)
    plt.plot(epochs, history['train_acc'], label='Độ chính xác (Train)', linestyle='-', marker='o', markersize=4)
    plt.plot(epochs, history['val_acc'], label='Độ chính xác (Validation)', linestyle='-', marker='x', markersize=4)
    plt.title('Độ chính xác (Accuracy)')
    plt.xlabel('Epoch')
    plt.ylabel('Độ chính xác')
    plt.legend()
    plt.grid(True)

    plt.figure(figsize=(19, 6))

    # --- Đồ thị MAE ---
    plt.subplot(131)
    plt.plot(epochs, history['train_mae'], label='MAE (Train)', linestyle='-', marker='o', markersize=4)
    plt.plot(epochs, history['val_mae'], label='MAE (Validation)', linestyle='-', marker='x', markersize=4)
    plt.title('Sai số tuyệt đối trung bình (MAE)')
    plt.xlabel('Epoch')
    plt.ylabel('MAE')
    plt.legend()
    plt.grid(True)

    # --- Đồ thị RMSE ---
    plt.subplot(132)
    plt.plot(epochs, history['train_rmse'], label='RMSE (Train)', linestyle='-', marker='o', markersize=4)
    plt.plot(epochs, history['val_rmse'], label='RMSE (Validation)', linestyle='-', marker='x', markersize=4)
    plt.title('Sai số toàn phương trung bình căn (RMSE)')
    plt.xlabel('Epoch')
    plt.ylabel('RMSE')
    plt.legend()
    plt.grid(True)

    # --- Đồ thị MSE ---
    plt.subplot(133)
    plt.plot(epochs, history['train_mse'], label='MSE (Train)', linestyle='-', marker='o', markersize=4)
    plt.plot(epochs, history['val_mse'], label='MSE (Validation)', linestyle='-', marker='x', markersize=4)
    plt.title('Sai số binh phương trung bình (MSE)')
    plt.xlabel('Epoch')
    plt.ylabel('MSE')
    plt.legend()
    plt.grid(True)

    # Tự động điều chỉnh khoảng cách giữa các subplot
    plt.tight_layout()
    # Hiển thị đồ thị
    plt.show()

def train_depth_estimation_model(model,
                                 train_dataset,
                                 val_dataset,
                                 loss_fn,
                                 optimizer,
                                 epochs,
                                 patience,
                                 size_img):

    history = {
        "train_loss": [], "train_acc": [], "train_mae": [], "train_rmse": [], "train_mse": [],
        "val_loss": [], "val_acc": [], "val_mae": [], "val_rmse": [], "val_mse": []
    }

    # Lưu tốc độ học ban đầu để hiển thị hoặc tham khảo
    initial_learning_rate = optimizer.learning_rate.numpy()
    print(f"Initial Learning Rate: {initial_learning_rate:.5f}")

    path_save_wights = f'/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/D-ANY/checkpoint_paper/Paper4_DENSE_UNET_{size_img[0]}_{size_img[1]}.weights.h5'
    best_val_loss = float('inf') # Hoặc có thể dùng best_val_loss = float('inf')
    epochs_without_improvement = 0


    for epoch in range(epochs):
        # Get the current time
        start_time = datetime.now()

        print(f"Epoch {epoch+1}/{epochs} ({len(train_dataset)}/{len(val_dataset)}) | ", end='')
        train_loss, train_acc, train_mae, train_rmse, train_mse = 0.0, 0.0, 0.0, 0.0, 0.0 # Khởi tạo
        steps = 0
        for X, y in train_dataset:
            # Nhận thêm metrics từ train_step_tf
            loss, acc, mae, rmse, mse = train_step_tf(model, X, y, loss_fn, optimizer)
            train_loss += loss.numpy()
            train_acc += acc.numpy()
            train_mae += mae.numpy() # Tích lũy
            train_rmse += rmse.numpy() # Tích lũy
            train_mse += mse.numpy() # Tích lũy
            steps += 1

        train_loss /= steps
        train_acc /= steps
        train_mae /= steps # Tính trung bình
        train_rmse /= steps # Tính trung bình
        train_mse /= steps # Tính trung bình

        val_loss, val_acc, val_mae, val_rmse, val_mse = 0.0, 0.0, 0.0, 0.0, 0.0 # Khởi tạo
        steps_val = 0
        for X, y in val_dataset:
            # Nhận thêm metrics từ validate_step_tf
            loss_val, acc_val, mae_val, rmse_val, mse_val = validate_step_tf(model, X, y, loss_fn)
            val_loss += loss_val.numpy()
            val_acc += acc_val.numpy()
            val_mae += mae_val.numpy() # Tích lũy
            val_rmse += rmse_val.numpy() # Tích lũy
            val_mse += mse_val.numpy() # Tích lũy
            steps_val += 1
        val_loss /= steps_val
        val_acc /= steps_val
        val_mae /= steps_val # Tính trung bình
        val_rmse /= steps_val # Tính trung bình
        val_mse /= steps_val # Tính trung bình

        history["train_loss"].append(train_loss)
        history["train_acc"].append(train_acc)
        history["train_mae"].append(train_mae) # Lưu vào history
        history["train_rmse"].append(train_rmse) # Lưu vào history
        history["train_mse"].append(train_mse) # Lưu vào history
        history["val_loss"].append(val_loss)
        history["val_acc"].append(val_acc)
        history["val_mae"].append(val_mae) # Lưu vào history
        history["val_rmse"].append(val_rmse) # Lưu vào history
        history["val_mse"].append(val_mse) # Lưu vào history
        end_time = datetime.now()
        print_msg = (
            f"Time (s): {(end_time - start_time).seconds}, "
            f"Train Loss: {train_loss:.5f}, Train Acc: {train_acc:.5f}, Train MAE: {train_mae:.5f}, Train RMSE: {train_rmse:.5f}, Train MSE: {train_mse:.5f}, "
            f"Val Loss: {val_loss:.5f}, Val Acc: {val_acc:.5f}, Val MAE: {val_mae:.5f}, Val RMSE: {val_rmse:.5f}, Val MSE: {val_mse:.5f}")

        print(print_msg) # In thông tin đầy đủ

        if val_loss < best_val_loss: # Hoặc if val_loss <= best_val_loss:
            print(f"  Improved {val_loss - best_val_loss :.5f} val_loss from {best_val_loss:.5f} to {val_loss:.5f}. Check points save !")
            best_val_loss = val_loss
            model.save_weights(path_save_wights)
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1

        if (epoch + 1) % (epochs // 10) == 0:
            # Có thể cập nhật plot_training_history để vẽ thêm MAE, RMSE nếu muốn
            plot_training_history(history)

        if epoch == 30 or epoch == 35:
            current_learning_rate = optimizer.learning_rate.numpy()
            new_learning_rate = current_learning_rate * 0.1
            optimizer.learning_rate.assign(new_learning_rate) # Cập nhật tốc độ học của optimizer
            print(f"\nEpoch {epoch+1}: Learning rate from {current_learning_rate:.7f} to {new_learning_rate:.7f}")

        if epochs_without_improvement >= patience:
            print(f"\nEarly stopping.")
            break

    model.load_weights(path_save_wights)
    return history

"""## Slices Data"""

import numpy as np
from sklearn.model_selection import train_test_split
from datetime import datetime

batch_size = 16

train_images = X_train.astype(np.float32)
train_depth_maps = y_train.astype(np.float32)
val_images = X_val.astype(np.float32)
val_depth_maps = y_val.astype(np.float32)

X_train, y_train, X_val, y_val = None,None,None,None

train_dataset = tf.data.Dataset.from_tensor_slices((train_images, train_depth_maps))
train_dataset = train_dataset.cache().shuffle(buffer_size=1024).batch(batch_size).prefetch(tf.data.AUTOTUNE)

val_dataset = tf.data.Dataset.from_tensor_slices((val_images, val_depth_maps))
val_dataset = val_dataset.batch(batch_size).prefetch(tf.data.AUTOTUNE)

train_images, train_depth_maps = None, None
val_images, val_depth_maps = None, None

print('done')

train_dataset, val_dataset

train_dataset, val_dataset = None, None

"""## Training

## paper 4: dense unet
"""

# Get the current time
start_time = datetime.now()
# Print the current time
print("Start Time:", start_time)

# loss_fn = tf.keras.losses.MeanSquaredError()  # Cho bài toán hồi quy MSE
loss_fn = combined_loss
# loss_fn = tf.keras.losses.Huber(delta=0.5)
# loss_fn = tf.keras.losses.MeanAbsoluteError()

# optimizer = tf.keras.optimizers.SGD(mome)
optimizer = tf.keras.optimizers.Adam(0.001)

# =====================================================================================================
print(f"loss THRESSHOD = {THRESSHOD}")
print(model.count_params())
print(f"So luong class: {len(model.layers)}")

_ = optimizer.build(model.trainable_variables) # optimizer.build() có thể thay đổi tốc độ học trong vòng lặp huấn luyện bằng phương thức. ví dụ: optimizer.learning_rate.assign(new_learning_rate)
# =====================================================================================================

epochs = 40
history10 = train_depth_estimation_model(
        model,
        train_dataset,
        val_dataset,
        loss_fn,
        optimizer,
        epochs,
        patience=10,
        size_img=(width, height)
    )

# Ví dụ: In ra các khóa lưu trong history sau khi huấn luyện
print("Các metric lưu trong history:", list(history10.keys()))

end_time = datetime.now()
print("Done at:", end_time)
print(f"Time (seconds): {(end_time - start_time).seconds}")

"""# SAVE WEIGHTS"""

model.save_weights('/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/D-ANY/checkpoint_paper/Paper4_DENSE_UNET_192_256_LuuThem.weights.h5')
#

"""# LOAD WEIGHTS"""

model.load_weights('/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/D-ANY/checkpoint_paper/Paper2_hamy_nets_192_256.weights.h5') # HSMY
# model.load_weights('/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/D-ANY/checkpoint_paper/Paper2_hamy_nets.weights.h5') # HSMY

model.load_weights('/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/ck_cae/model_CAE_192_256.weights.h5') # CAE

model.load_weights('/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/ck_res/model_U1_192_256.weights.h5') # UNET
# /content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE/Unet_Resnet_All.csv

"""# SAVED HISTORY TRAINED"""

import pandas as pd

df = pd.DataFrame(history10)
df.to_csv('/content/drive/MyDrive/KLTN_LeQuangVinh_19503031/FINAL_CODE_COLAB/D-ANY/checkpoint_paper/CSV_Paper4_DENSE_UNET_192_256.csv')

df.tail(10)

"""# PREDICT IMAGE"""

import cv2
import numpy as np

def lam_sat_net_float_sau_median_ngan(anh_xam_float, kich_thuoc_median=3, kich_thuoc_gaussian=(3, 3), luong_sac_net=1.0):
    """Làm sắt nét ảnh xám (float 0-1) sau lọc median."""
    # Chuyển tạm sang uint8 cho median blur, sau đó về float 0-1
    anh_uint8 = (anh_xam_float * 255.0).astype(np.uint8)
    anh_sau_median_uint8 = cv2.medianBlur(anh_uint8, kich_thuoc_median)
    anh_sau_median_float = anh_sau_median_uint8.astype(np.float32) / 255.0

    # Unsharp Masking

    # anh_mo_float = cv2.medianBlur(anh_sau_median_float, kich_thuoc_median)
    anh_mo_float = cv2.GaussianBlur(anh_sau_median_float, kich_thuoc_gaussian, 0)
    mask = anh_sau_median_float - anh_mo_float
    anh_sac_net_float = anh_sau_median_float + luong_sac_net * mask

    # Giới hạn về 0-1
    anh_sac_net_float = np.clip(anh_sac_net_float, 0.0, 1.0)

    return anh_sac_net_float

def remove_outliers_per_image(images, z_thresh=10.0):
    """
    Loại bỏ các điểm ảnh ngoại lai trong mỗi ảnh bằng phương pháp z-score.
    Các điểm ảnh có z-score > z_thresh sẽ được thay bằng giá trị trung vị của ảnh.
    images: numpy array, shape (N, H, W) hoặc (N, H, W, 1)
    z_thresh: ngưỡng z-score để xác định ngoại lai
    """
    images_out = []
    for img in images:
        img_flat = img.flatten()
        mean = np.mean(img_flat)
        std = np.std(img_flat)
        if std == 0:
            images_out.append(img)
            continue
        z_scores = (img_flat - mean) / std
        mask = np.abs(z_scores) > z_thresh
        img_flat[mask] = np.median(img_flat)
        img_out = img_flat.reshape(img.shape)
        images_out.append(img_out)
    return np.array(images_out)

y_pred = model.predict(X_test)
y_pred = np.squeeze(y_pred)

# Nếu y_pred có shape (N, H, W, 1) thì squeeze về (N, H, W)
if y_pred.ndim == 4 and y_pred.shape[-1] == 1:
    y_pred_proc = np.squeeze(y_pred, axis=-1)
else:
    y_pred_proc = y_pred

# y_pred = [lam_sat_net_float_sau_median_ngan(image) for image in y_pred]
# y_pred = [lam_sat_net_float_sau_median_ngan(image) for image in y_pred]
# y_pred = remove_outliers_per_image(y_pred,20)
# y_pred = remove_outliers_per_image(y_pred,8)
# y_pred = remove_outliers_per_image(y_pred,8)
# y_pred = remove_outliers_per_image(y_pred)
# y_pred = remove_outliers_per_image(y_pred)
# y_pred = remove_outliers_per_image(y_pred)
y_pred = np.array(y_pred).astype(np.float32)

"""## DENSE UNET (P4)"""

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def describe_Image(image):
    df = pd.DataFrame(np.squeeze(image).flatten()).describe()
    return df[0].to_dict()

max_values_y_test = np.array([np.max(x) for x in y_test])
sort_indices = np.argsort(max_values_y_test)

y_test_sorted = np.array(y_test)[sort_indices]
y_pre_sorted = y_pred[sort_indices]

_median = [np.median(x) for x in y_test_sorted]
_median_pre = [np.median(x) for x in y_pre_sorted]
y_des = [describe_Image(x) for x in y_test_sorted]
y_des_pre = [describe_Image(x) for x in y_pre_sorted]

# Vẽ lại biểu đồ với dữ liệu đã sắp xếp
# fig.patch.set_visible(False)  # Ẩn khung hình chính
plt.figure(figsize=(20, 15))
# Biểu đồ 1: Đường
plt.plot(range(len(y_test_sorted)), _median, label='MEDIAN', color='red')
plt.plot(range(len(y_test_sorted)), _median_pre, label='MEDIAN PREDICT', color='green')

plt.plot(range(len(y_test_sorted)), [item['max'] for item in y_des], label='MAX', color='magenta')
plt.plot(range(len(y_test_sorted)), [item['max'] for item in y_des_pre], label='MAX PREDICT', color='black')

plt.plot(range(len(y_test_sorted)), [item['mean'] for item in y_des], label='MEAN', color='blue')
plt.plot(range(len(y_test_sorted)), [item['mean'] for item in y_des_pre], label='MEAN PREDICT', color='yellow')

plt.plot(range(len(y_test_sorted)), [item['min'] for item in y_des], label='MIN', color='black')
plt.plot(range(len(y_test_sorted)), [item['min'] for item in y_des_pre], label='MIN PREDICT', color='orange')

plt.legend(loc='upper left')
plt.grid(True)

plt.show()

depth_values = None
depth_pre_values = None
y_des = None
y_pre_sorted = None
y_test_sorted = None

def VisualizeResults(index):

    pred_y = y_pred[index]

    actual_depth = y_test[index, :, :, 0]
    pre_img = np.squeeze(pred_y)

    fig = plt.figure(figsize=(40, 10))
    gs = gridspec.GridSpec(1, 4, figure=fig)

    # Subplot 2: GT Depth
    ax2 = fig.add_subplot(gs[0, 0])
    ax2.imshow(actual_depth, 'gray')
    ax2.set_title(f'GT Depth')

    # Subplot 4: Predicted Depth
    ax5 = fig.add_subplot(gs[0, 1])
    ax5.imshow(pre_img, 'gray')
    ax5.set_title(f'Predicted Depth')

    # Subplot 5: Violin Predicted
    ax6 = fig.add_subplot(gs[0, 2])
    sns.violinplot(y=actual_depth.flatten(), inner="quart", label="GT" , color='red', ax=ax6, alpha=0.6)
    sns.violinplot(y=pre_img.flatten(), inner="quart", label='PREDICT', color='blue', ax=ax6, alpha=0.6)
    # sns.violinplot(y=abs(actual_depth.flatten() - pre_img.flatten()), inner="quart", label='DEF', alpha=0.6, color='yellow', ax=ax6)
    ax6.set_title(f'Violin frequency')
    ax6.legend()

    ax7 = fig.add_subplot(gs[0, 3])
    sns.histplot(actual_depth.flatten(), kde=True, label="GT", color='red', ax=ax7)
    sns.histplot(pre_img.flatten(), kde=True, label="PREDICT", color='blue', ax=ax7)
    # sns.histplot(np.abs(actual_depth - pre_img).flatten(), kde=True, label="DEFFERENT", alpha=0.5, color='yellow', ax=ax7)
    ax7.set_title(f'Histogram frequency')
    ax7.legend()

    plt.show()

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import matplotlib.gridspec as gridspec

for index in range(0, X_test.shape[0], X_test.shape[0]//30):
    VisualizeResults(index)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec # Import gridspec
import seaborn as sns # Import seaborn

def evaluate_accuracy(y_true, y_pred, threshold=0.0):
  diff = np.abs(y_true - y_pred)
  correct_pixels = np.sum(diff <= threshold)
  total_pixels = y_true.size
  accuracy = correct_pixels / total_pixels
  return accuracy

def visualize_3d_histogram_depth_comparison(depth_true, depth_pred, bins=40, label=None, index=0):

    fig = plt.figure(figsize=(40, 10))
    # Define gs here within the function
    gs = gridspec.GridSpec(1, 4, figure=fig)  # Adjust the grid as needed
    # Subplot 1: Processed Image
    ax1 = fig.add_subplot(gs[0, 0])
    ax1.imshow(depth_true, 'gray')
    ax1.set_title('Depth GT')

    # Subplot 2: GT Depth
    ax2 = fig.add_subplot(gs[0, 1])
    ax2.imshow(depth_pred, 'gray')
    ax2.set_title(f'Depth PRED')

    # 1. Chuẩn bị dữ liệu
    depth_true_flat = depth_true.flatten()
    depth_pred_flat = depth_pred.flatten()

    # Subplot 6: Histogram
    ax7 = fig.add_subplot(gs[0, 2]) # Change subplot index if necessary
    sns.histplot(depth_true_flat, kde=True, label="GT", color='blue', ax=ax7)
    sns.histplot(depth_pred_flat, kde=True, label="PREDICT", alpha=0.3, color='red', ax=ax7)
    ax7.set_title(f'Histogram frequency')
    ax7.legend()


    ax9 = fig.add_subplot(gs[0, 3])
    sns.scatterplot(x=depth_true_flat, y=depth_pred_flat, s=20, alpha=0.4, label='GT VS PRED', ax=ax9, color='red')
    sns.scatterplot(x=depth_true_flat, y=depth_true_flat, s=20, alpha=0.4, label='GT VS GT', ax=ax9, color='blue')
    ax9.set_xlabel("Actual Depth")
    ax9.set_ylabel("Predicted Depth")
    acc = evaluate_accuracy(depth_true_flat, depth_pred_flat, threshold=0.1)
    ax9.set_title(f"Scatter Plot GT Vs PRED {np.float16(acc)}")
    ax9.grid(True)
    ax9.legend()

    # plt.savefig(f"../224_2000/cfmt_2d_model_3_epochs_{index}.png")
    plt.show()

for index in range(0, y_test.shape[0], y_test.shape[0] // 30):
    y_pre = y_pred[index]
    visualize_3d_histogram_depth_comparison(y_test[index], y_pre, label="FREQUENCY__CFMT_2D",index=index)

"""# DO CHINH XAC ACC"""

import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

def evaluate_image_similarity(real_image, predicted_image):

    # Flatten the images into 1D vectors
    real_image_flat = real_image.flatten()
    predicted_image_flat = predicted_image.flatten()

    # Ensure the input arrays are 2D for cosine_similarity
    real_image_2d = real_image_flat.reshape(1, -1)
    predicted_image_2d = predicted_image_flat.reshape(1, -1)

    # Calculate the cosine similarity
    similarity = cosine_similarity(real_image_2d, predicted_image_2d)[0][0]
    return similarity

def evaluate_accuracy(y_true, y_pred, threshold=0.0):
  diff = np.abs(y_true - y_pred)
  correct_pixels = np.sum(diff <= threshold)
  total_pixels = y_true.size # 224 * 224 = 50176
  accuracy = correct_pixels / total_pixels
  return accuracy, diff

print(f'test: {y_test.shape}')
print(f'predict: {y_pred.shape}')
threshold = 0.02
accs = []

y_pred = model.predict(X_test)
y_pred = np.squeeze(y_pred)

accs = [float(evaluate_accuracy(np.squeeze(y_test[i]), np.squeeze(y_pred[i]), threshold=threshold)[0]) for i in range(y_pred.shape[0]-1)]
print(accs)
print("Trung bình độ chính xác:", np.mean(accs), f'\nVới ngưỡng tỉ lệ sai cho phép threshold = {threshold}')

print()
accs_similar = [float(evaluate_image_similarity(np.squeeze(y_test[i]), np.squeeze(y_pred[i]))) for i in range(y_pred.shape[0]-1)]
print(accs_similar)
print("Trung bình độ chính xác cosine similar:", np.mean(accs_similar))

"""## UNRT DENSE (P4)"""

import numpy as np

best_index_3D, worst_index_3D = [], []

for threshold in [0.4, 0.3, 0.2, 0.1, 0.05, 0.02, 0.015, 0.01, 0.001]:
    print(f'THRESSHOD: {threshold}')
    # Tính độ chính xác cho từng ảnh
    accuracies = accs_similar = [float(evaluate_accuracy(np.squeeze(y_test[i]), np.squeeze(y_pred[i]), threshold=threshold)[0]) for i in range(y_pred.shape[0]-1)]

    # Lấy chỉ số ảnh có độ chính xác cao nhất
    best_index = np.argmax(accuracies)
    worst_index = np.argmin(accuracies)
    best_index_3D.append(best_index)
    worst_index_3D.append(worst_index)
    best_accuracy = accuracies[best_index]
    worst_accuracy = accuracies[worst_index]

    print(f"ACCURACY BEST: {best_accuracy}")

    plt.figure(figsize=(12,8))
    plt.imshow(y_test[best_index])
    plt.axis(False)
    plt.tight_layout()
    plt.show()

    plt.figure(figsize=(12,8))
    plt.imshow(y_pred[best_index])
    plt.axis(False)
    plt.tight_layout()
    plt.show()

    print(f"ACCURACY WORST: {worst_accuracy}")

    # plt.figure(figsize=(12,8))
    # plt.imshow(X_test[worst_index])
    # plt.axis(False)
    # plt.show()

    plt.figure(figsize=(12,8))
    plt.imshow(y_test[worst_index])
    plt.axis(False)
    plt.tight_layout()
    plt.show()

    plt.figure(figsize=(12,8))
    plt.imshow(y_pred[worst_index])
    plt.axis(False)
    plt.tight_layout()
    plt.show()

    for index in [best_index, worst_index]:
        y_true = y_test[index]
        mask_path = matrix_test[index, 2]

        y_pre = y_pred[index]

        img_mask = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED)
        img_mask = cv2.resize(img_mask.copy(), (height, width), cv2.INTER_AREA)

        new_mask = np.where(img_mask.copy() > 0, 255, 0).astype(np.uint8)
        kernel = np.ones(shape=(3,3))
        new_mask = cv2.dilate(new_mask, kernel, iterations=1)

        # Tìm đường viền của các đối tượng màu trắng
        contours, hierarchy = cv2.findContours(new_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        y_true_mask = y_true.copy()
        y_pred_mask = y_pre.copy()

        print(y_true_mask.shape, y_pred_mask.shape)

        # Duyệt qua từng đường viền tìm được
        for contour in contours:
                # Lấy tọa độ và kích thước của bounding box
                x, y, w, h = cv2.boundingRect(contour)

                # Vẽ hình chữ nhật (bounding box) xung quanh đối tượng
                cv2.rectangle(y_true_mask, (x, y), (x + w, y + h), (0, 128, 0), 1) # Màu đỏ, độ dày 2
                cv2.rectangle(y_pred_mask, (x, y), (x + w, y + h), (0, 128, 0), 1) # Màu đỏ, độ dày 2

        print(f"ACCURACY WITH MASK: {accs[index]}")

        plt.figure(figsize=(12, 8))
        plt.imshow(y_true_mask)
        plt.axis(False)
        plt.tight_layout()
        plt.show()

        plt.figure(figsize=(12, 8))
        plt.imshow(y_pred_mask)
        plt.axis(False)
        plt.tight_layout()
        plt.show()

"""## DENSE UNET (P4)"""

for i in [0, 186,915,893,1145,334,335]:

    index_img = i
    plt.imshow(X_test[index_img])
    plt.axis(False)
    plt.show()

    plt.imshow(y_test[index_img], cmap='gray')
    plt.axis(False)
    plt.show()

    plt.imshow(y_pred[index_img], cmap='gray')
    plt.axis(False)
    plt.show()

    plt.figure(figsize=(6,6))
    sns.violinplot(y=y_test[index_img].flatten(), inner="quart", label="GT" , color='red', alpha=0.6)
    sns.violinplot(y=y_pred[index_img].flatten(), inner="quart", label='PREDICT', color='blue', alpha=0.6)
    plt.legend()
    plt.show()

    plt.figure(figsize=(6,6))
    sns.histplot(y_test[index_img].flatten(), kde=True, label="GT", color='blue')
    sns.histplot(y_pred[index_img].flatten(), kde=True, label="PREDICT", alpha=0.3, color='red')
    plt.legend()
    plt.grid(True)
    plt.show()

    plt.figure(figsize=(6,6))
    sns.scatterplot(x=y_test[index_img].flatten(), y=y_pred[index_img].flatten(), s=20, alpha=0.4, label='GT VS PRED', color='red')
    sns.scatterplot(x=y_test[index_img].flatten(), y=y_test[index_img].flatten(), s=20, alpha=0.4, label='GT VS GT', color='blue')
    plt.legend()
    plt.grid(True)
    plt.show()

for i in [np.int64(495),
  np.int64(499),
  np.int64(854),
  np.int64(650),
  np.int64(1079),
  np.int64(79)]:

    index_img = i
    plt.imshow(X_test[index_img])
    plt.axis(False)
    plt.show()

    plt.imshow(y_test[index_img], cmap='gray')
    plt.axis(False)
    plt.show()

    plt.imshow(y_pred[index_img], cmap='gray')
    plt.axis(False)
    plt.show()

    plt.figure(figsize=(6,6))
    sns.violinplot(y=y_test[index_img].flatten(), inner="quart", label="GT" , color='red', alpha=0.6)
    sns.violinplot(y=y_pred[index_img].flatten(), inner="quart", label='PREDICT', color='blue', alpha=0.6)
    plt.legend()
    plt.show()

    plt.figure(figsize=(6,6))
    sns.histplot(y_test[index_img].flatten(), kde=True, label="GT", color='blue')
    sns.histplot(y_pred[index_img].flatten(), kde=True, label="PREDICT", alpha=0.3, color='red')
    plt.legend()
    plt.grid(True)
    plt.show()

    plt.figure(figsize=(6,6))
    sns.scatterplot(x=y_test[index_img].flatten(), y=y_pred[index_img].flatten(), s=20, alpha=0.4, label='GT VS PRED', color='red')
    sns.scatterplot(x=y_test[index_img].flatten(), y=y_test[index_img].flatten(), s=20, alpha=0.4, label='GT VS GT', color='blue')
    plt.legend()
    plt.grid(True)
    plt.show()

"""# DO TUONG DONG COSINE"""

import numpy as np

def evaluate_image_similarity(real_image, predicted_image):

    # Flatten the images into 1D vectors
    real_image_flat = real_image.flatten()
    predicted_image_flat = predicted_image.flatten()

    # Ensure the input arrays are 2D for cosine_similarity
    real_image_2d = real_image_flat.reshape(1, -1)
    predicted_image_2d = predicted_image_flat.reshape(1, -1)

    # Calculate the cosine similarity
    similarity = cosine_similarity(real_image_2d, predicted_image_2d)[0][0]
    return similarity

# Tính độ chính xác cho từng ảnh
accuracies = accs_similar = [float(evaluate_image_similarity(np.squeeze(y_test[i]), cv2.medianBlur(np.squeeze(y_pred[i]),3) )) for i in range(y_pred.shape[0]-1)]

# Lấy chỉ số ảnh có độ chính xác cao nhất
best_index = np.argmax(accuracies)
worst_index = np.argmin(accuracies)
best_accuracy = accuracies[best_index]
worst_accuracy = accuracies[worst_index]

print(f"SIMILAR BEST: {best_accuracy}")

# plt.figure(figsize=(12,8))
# plt.imshow(X_test[best_index])
# plt.axis(False)
# plt.show()
# y_pred[worst_index][y_pred[worst_index] > 0.93] = 0
# y_pred[worst_index][y_pred[worst_index] > 0.98] = 0
plt.figure(figsize=(12,8))
plt.imshow(y_test[best_index], cmap='gray')
plt.axis(False)
plt.tight_layout()
plt.show()

plt.figure(figsize=(12,8))
plt.imshow(y_pred[best_index], cmap='gray')
plt.axis(False)
plt.tight_layout()
plt.show()

print(f"SIMILAR WORST: {worst_accuracy}")

# plt.figure(figsize=(12,8))
# plt.imshow(X_test[worst_index])
# plt.axis(False)
# plt.show()

plt.figure(figsize=(12,8))
plt.imshow(y_test[worst_index], cmap='gray')
plt.axis(False)
plt.tight_layout()
plt.show()

plt.figure(figsize=(12,8))
plt.imshow(y_pred[worst_index], cmap='gray')
plt.axis(False)
plt.tight_layout()
plt.show()

for index in [best_index, worst_index]:
    y_true = y_test[index]
    mask_path = matrix_test[index, 2]

    y_pre = y_pred[index]

    img_mask = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED)
    img_mask = cv2.resize(img_mask.copy(), (height, width), cv2.INTER_AREA)

    new_mask = np.where(img_mask.copy() > 0, 255, 0).astype(np.uint8)
    kernel = np.ones(shape=(3,3))
    new_mask = cv2.dilate(new_mask, kernel, iterations=1)

    # Tìm đường viền của các đối tượng màu trắng
    contours, hierarchy = cv2.findContours(new_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    y_true_mask = y_true.copy()
    y_pred_mask = y_pre.copy()

    print(y_true_mask.shape, y_pred_mask.shape)

    # Duyệt qua từng đường viền tìm được
    for contour in contours:
            # Lấy tọa độ và kích thước của bounding box
            x, y, w, h = cv2.boundingRect(contour)

            # Vẽ hình chữ nhật (bounding box) xung quanh đối tượng
            cv2.rectangle(y_true_mask, (x, y), (x + w, y + h), (0, 128, 0), 1) # Màu đỏ, độ dày 2
            cv2.rectangle(y_pred_mask, (x, y), (x + w, y + h), (0, 128, 0), 1) # Màu đỏ, độ dày 2

    print(f"SIMILAR WITH MASK: {accs[index]}")

    plt.figure(figsize=(12, 8))
    plt.imshow(y_true_mask)
    plt.axis(False)
    plt.tight_layout()
    plt.show()

    plt.figure(figsize=(12, 8))
    plt.imshow(y_pred_mask)
    plt.axis(False)
    plt.tight_layout()
    plt.show()

"""# DANH GIA MO HINH"""

import tensorflow as tf
import numpy as np

# Đảm bảo y_test và y_pred có shape (N, H, W)
if y_test.ndim == 4 and y_test.shape[-1] == 1:
    y_test_ = np.squeeze(y_test, axis=-1)
else:
    y_test_ = y_test

if y_pred.ndim == 4 and y_pred.shape[-1] == 1:
    y_pred_ = np.squeeze(y_pred, axis=-1)
else:
    y_pred_ = y_pred

# Tính SSIM cho từng cặp ảnh
ssim_scores = []
for i in range(y_test.shape[0]):
    img_true = y_test[i]
    img_pred = y_pred[i]
    # Ensure shape is (H, W, 1) for tf.image.ssim
    if img_true.ndim == 2:
        img_true = np.expand_dims(img_true, axis=-1)
    if img_pred.ndim == 2:
        img_pred = np.expand_dims(img_pred, axis=-1)
    ssim_val = tf.image.ssim(img_true, img_pred, max_val=1.0).numpy()
    ssim_scores.append(ssim_val)

ssim_scores = np.array(ssim_scores)
mean_ssim = np.mean(ssim_scores)
mean_ssim_loss = 1.0 - mean_ssim

print(f"Trung bình SSIM: {mean_ssim:.4f}")
print(f"Trung bình sai số SSIM (1-SSIM): {mean_ssim_loss:.4f}")

import numpy as np
y_test = np.squeeze(y_test)
mse = np.mean((y_pred - y_test) ** 2)
print(f"Trung bình sai số MSE: {mse:.6f}")

mae = tf.reduce_mean(np.abs(y_pred - y_test))
print(f"Trung bình sai số MAE: {mae}")

import numpy as np

# Tính RMSE cho từng cặp ảnh
rmse_list = [np.sqrt(np.mean((np.squeeze(y_test[i]) - np.squeeze(y_pred[i])) ** 2)) for i in range(y_test.shape[0])]
mean_rmse = np.mean(rmse_list)

print(f"Tổng trung bình sai số RMSE: {mean_rmse:.6f}")

"""# DANH GIA KHOANG CACH"""

def calculate_amd(points1, points2):
    """
    Tính Average Minimum Distance giữa hai tập điểm.

    Args:
        points1 (np.ndarray): Tập điểm thứ nhất (shape: N1 x D).
        points2 (np.ndarray): Tập điểm thứ hai (shape: N2 x D).

    Returns:
        float: Average Minimum Distance.
    """
    if len(points1) == 0 or len(points2) == 0:
        return float('inf') # Trả về vô cùng nếu một trong hai tập rỗng

    # Sử dụng cKDTree để tìm điểm gần nhất hiệu quả
    from scipy.spatial import cKDTree

    # Tính khoảng cách từ mỗi điểm trong points1 đến điểm gần nhất trong points2
    tree2 = cKDTree(points2)
    distances1_to_2, _ = tree2.query(points1)
    dist_1_to_2 = np.mean(distances1_to_2)

    # Tính khoảng cách từ mỗi điểm trong points2 đến điểm gần nhất trong points1
    tree1 = cKDTree(points1)
    distances2_to_1, _ = tree1.query(points2)
    dist_2_to_1 = np.mean(distances2_to_1)

    # Tính AMD đối xứng
    amd = (dist_1_to_2 + dist_2_to_1) / 2.0

    return amd

def image_to_points(image, threshold_depth=0.02, normalize_coords=False):
    """
    Chuyển ảnh độ sâu thành tập điểm (x, y, depth).

    Args:
        image (np.ndarray): Ảnh độ sâu (shape: H x W).
        threshold_depth (float): Ngưỡng độ sâu tối thiểu để coi là điểm hợp lệ.
        normalize_coords (bool): Có chuẩn hóa tọa độ x, y về [0, 1] không.

    Returns:
        np.ndarray: Tập điểm (N x 3), mỗi hàng là [x, y, depth].
    """
    points = []
    height, width = image.shape[:2]

    if normalize_coords:
        max_val = np.max(image) if np.max(image) > 0 else 1.0 # Tránh chia cho 0
    else:
        max_val = 1.0 # Không chuẩn hóa giá trị độ sâu nếu normalize_coords=False


    for r in range(height):
        for c in range(width):
            depth_value = image[r, c]
            if depth_value > threshold_depth:
                if normalize_coords:
                    points.append([c / (width - 1), r / (height - 1), depth_value / max_val])
                else:
                    points.append([c, r, depth_value])

    return np.array(points)

# =============================================================================
# Tính AMD cho tập test
amd_scores = []
# Chọn ngưỡng độ sâu tối thiểu cho các điểm
depth_threshold = 0.02 # Điều chỉnh ngưỡng này tùy thuộc vào dữ liệu của bạn

# y_test và y_pred đã được tải và tiền xử lý trước đó
# Đảm bảo chúng có shape (N, H, W) hoặc (N, H, W, 1) và giá trị đã được scale

# Squeeze chiều cuối nếu có
if y_test.ndim == 4 and y_test.shape[-1] == 1:
    y_test_sq = np.squeeze(y_test, axis=-1)
else:
     y_test_sq = y_test

if y_pred.ndim == 4 and y_pred.shape[-1] == 1:
    y_pred_sq = np.squeeze(y_pred, axis=-1)
else:
    y_pred_sq = y_pred

print(f"Calculating AMD for {y_test_sq.shape[0]} pairs of images...")
# Có thể giới hạn số lượng ảnh để tính toán nhanh hơn
# for i in range(min(y_test_sq.shape[0], 100)): # Ví dụ: chỉ tính cho 100 ảnh đầu tiên
for i in range(y_test_sq.shape[0]):
    if i % 50 == 0:
        print(f"Processing image {i+1}/{y_test_sq.shape[0]}")

    # Chuyển từng ảnh thành tập điểm
    points_true = image_to_points(y_test_sq[i], threshold_depth=depth_threshold, normalize_coords=False) # Chọn normalize_coords tùy ý
    points_pred = image_to_points(y_pred_sq[i], threshold_depth=depth_threshold, normalize_coords=False) # Chọn normalize_coords tùy ý

    # Tính AMD cho cặp ảnh này
    amd = calculate_amd(points_true, points_pred)
    amd_scores.append(amd)

# Tính trung bình AMD trên toàn bộ tập test
mean_amd = np.mean(amd_scores) if amd_scores else 0.0

print(f"\nTrung bình Average Minimum Distance (AMD) trên tập test: {mean_amd:.6f}")

# Sử dụng scipy.spatial.distance.directed_hausdorff
from scipy.spatial.distance import directed_hausdorff
from scipy.spatial import cKDTree # Import cKDTree for efficient nearest neighbor search

def calculate_hausdorff(points1, points2):
    """
    Tính Khoảng cách Hausdorff giữa hai tập điểm.

    Args:
        points1 (np.ndarray): Tập điểm thứ nhất (shape: N1 x D).
        points2 (np.ndarray): Tập điểm thứ hai (shape: N2 x D).

    Returns:
        float: Khoảng cách Hausdorff đối xứng.
    """
    if len(points1) == 0 or len(points2) == 0:
        # Trường hợp một trong hai tập rỗng, khoảng cách Hausdorff là vô cùng
        return float('inf')

    # Tính khoảng cách Hausdorff có hướng từ points1 đến points2
    h1_to_2 = directed_hausdorff(points1, points2)[0]

    # Tính khoảng cách Hausdorff có hướng từ points2 đến points1
    h2_to_1 = directed_hausdorff(points2, points1)[0]

    # Khoảng cách Hausdorff đối xứng là giá trị lớn nhất trong hai khoảng cách có hướng
    hausdorff_dist = max(h1_to_2, h2_to_1)

    return hausdorff_dist

# =============================================================================
# Tính Hausdorff Distance cho tập test
hausdorff_scores = []
# Chọn ngưỡng độ sâu tối thiểu cho các điểm
# Sử dụng lại depth_threshold và y_test_sq, y_pred_sq từ phần tính AMD

print(f"Calculating Hausdorff Distance for {y_test_sq.shape[0]} pairs of images...")

for i in range(y_test_sq.shape[0]):
    if i % 50 == 0:
        print(f"Processing image {i+1}/{y_test_sq.shape[0]}")

    # Chuyển từng ảnh thành tập điểm
    # Quan trọng: Đối với Hausdorff Distance, bạn có thể muốn chỉ xem xét các điểm quan trọng
    # như ranh giới hoặc các điểm có giá trị độ sâu cao hơn ngưỡng.
    # Sử dụng hàm image_to_points đã định nghĩa.
    points_true = image_to_points(y_test_sq[i], threshold_depth=depth_threshold, normalize_coords=False) # Chọn normalize_coords tùy ý
    points_pred = image_to_points(y_pred_sq[i], threshold_depth=depth_threshold, normalize_coords=False) # Chọn normalize_coords tùy ý

    # Tính Hausdorff Distance cho cặp ảnh này
    # Lưu ý: directed_hausdorff yêu cầu ít nhất 2 điểm trong mỗi tập.
    if len(points_true) < 2 or len(points_pred) < 2:
        print(f"  Warning: Skipping image {i} due to insufficient points ({len(points_true)}/{len(points_pred)})")
        hausdorff_scores.append(float('inf')) # Hoặc np.nan nếu muốn bỏ qua
        continue

    try:
        hausdorff = calculate_hausdorff(points_true, points_pred)
        hausdorff_scores.append(hausdorff)
    except Exception as e:
        print(f"  Error calculating Hausdorff for image {i}: {e}")
        hausdorff_scores.append(float('inf')) # Hoặc np.nan

# Tính trung bình Hausdorff Distance (loại bỏ giá trị vô cùng nếu có)
finite_hausdorff_scores = [score for score in hausdorff_scores if score != float('inf')]

if finite_hausdorff_scores:
    mean_hausdorff = np.mean(finite_hausdorff_scores)
    print(depth_threshold)
    print(f"\nTrung bình Khoảng cách Hausdorff trên tập test ({len(finite_hausdorff_scores)}/{len(hausdorff_scores)} ảnh): {mean_hausdorff:.6f}")
else:
    print("\nKhông thể tính toán Khoảng cách Hausdorff cho bất kỳ ảnh nào.")

# prompt: tính Jaccard Distance giữa y_pred và y_test

def jaccard_distance(y_true, y_pred, threshold=0.02):
    """
    Tính Jaccard Distance giữa hai ảnh (được nhị phân hóa bằng ngưỡng).

    Args:
        y_true (np.ndarray): Ảnh ground truth (shape: H x W).
        y_pred (np.ndarray): Ảnh dự đoán (shape: H x W).
        threshold (float): Ngưỡng để nhị phân hóa ảnh.

    Returns:
        float: Jaccard Distance (1 - Jaccard Index).
    """
    # Nhị phân hóa ảnh
    y_true_binary = (y_true > threshold).astype(np.uint8)
    y_pred_binary = (y_pred > threshold).astype(np.uint8)

    # Tính toán Intersection (AND) và Union (OR)
    intersection = np.logical_and(y_true_binary, y_pred_binary).sum()
    union = np.logical_or(y_true_binary, y_pred_binary).sum()

    # Tránh chia cho 0
    if union == 0:
        return 1.0 # Nếu cả hai tập rỗng, Jaccard Distance là 1

    # Tính Jaccard Index và Jaccard Distance
    jaccard_index = intersection / union
    jaccard_dist = 1.0 - jaccard_index

    return jaccard_dist

# =============================================================================
# Tính Jaccard Distance cho tập test
jaccard_scores = []
# Sử dụng lại y_test_sq và y_pred_sq đã được squeeze

print(f"Calculating Jaccard Distance for {y_test_sq.shape[0]} pairs of images...")
# Có thể điều chỉnh ngưỡng nhị phân hóa
binary_threshold = 0.02

for i in range(y_test_sq.shape[0]):
    if i % 50 == 0:
        print(f"Processing image {i+1}/{y_test_sq.shape[0]}")

    # Tính Jaccard Distance cho cặp ảnh này
    jaccard_dist = jaccard_distance(y_test_sq[i], y_pred_sq[i], threshold=binary_threshold)
    jaccard_scores.append(jaccard_dist)

# Tính trung bình Jaccard Distance trên toàn bộ tập test
mean_jaccard_dist = np.mean(jaccard_scores) if jaccard_scores else 0.0

print(f"\nTrung bình Jaccard Distance trên tập test (ngưỡng nhị phân hóa = {binary_threshold}): {mean_jaccard_dist:.6f}")

# prompt: Tính Wasserstein Distance cho y_test và y_pred

!pip install pot
import ot

# Chuyển ảnh về dạng 1D histogram/distribution
# Flatten ảnh và loại bỏ các giá trị không hợp lệ (NaNs, Infs nếu có)
def image_to_distribution(image):
    flat_image = np.array(image).flatten()
    # Loại bỏ các giá trị không hợp lệ nếu có
    valid_values = flat_image[np.isfinite(flat_image)]
    # Nếu không có giá trị hợp lệ, trả về mảng rỗng hoặc xử lý theo logic của bạn
    if len(valid_values) == 0:
        return np.array([])
    # Tạo histogram hoặc chỉ sử dụng các giá trị duy nhất và tần suất của chúng
    # Để sử dụng trong ot.emd, cần có hai phân phối xác suất (tổng bằng 1)
    hist, bin_edges = np.histogram(valid_values, bins=100, density=False) # density=True để chuẩn hóa
    # Sử dụng các điểm giữa của các bin làm vị trí (locations)
    bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2.0
    return bin_centers, hist

wasserstein_distances = []

print(f"Calculating Wasserstein Distance for {y_test.shape[0]} pairs of images...")

# Có thể giới hạn số lượng ảnh để tính toán nhanh hơn
# for i in range(min(y_test.shape[0], 100)): # Ví dụ: chỉ tính cho 100 ảnh đầu tiên
for i in range(y_test.shape[0]):
    if i % 50 == 0:
        print(f"Processing image {i+1}/{y_test.shape[0]}")

    # Chuyển từng ảnh về phân phối
    locations_true, hist_true = image_to_distribution(y_test[i])
    locations_pred, hist_pred = image_to_distribution(y_pred[i])

    # Kiểm tra nếu một trong hai phân phối rỗng
    if len(locations_true) == 0 or len(locations_pred) == 0:
        print(f"  Warning: Skipping image {i} due to empty distribution")
        wasserstein_distances.append(np.nan) # Hoặc float('inf')
        continue

    # Tính ma trận chi phí (Cost matrix)
    # Sử dụng khoảng cách Euclidean giữa các vị trí
    try:
        cost_matrix = ot.dist(locations_true.reshape(-1, 1), locations_pred.reshape(-1, 1))

        # Tính Wasserstein Distance (Earth Mover's Distance - EMD)
        # hist_true và hist_pred phải có tổng bằng 1 để là phân phối xác suất
        # numpy.histogram với density=True đã làm điều này
        wasserstein_dist = ot.emd2(hist_true, hist_pred, cost_matrix)
        wasserstein_distances.append(wasserstein_dist)

    except Exception as e:
        print(f"  Error calculating Wasserstein distance for image {i}: {e}")
        wasserstein_distances.append(np.nan)


# Tính trung bình Wasserstein Distance (loại bỏ giá trị NaN nếu có)
finite_wasserstein_distances = [dist for dist in wasserstein_distances if not np.isnan(dist)]

if finite_wasserstein_distances:
    mean_wasserstein_dist = np.mean(finite_wasserstein_distances)
    print(f"\nTrung bình Wasserstein Distance (EMD) trên tập test ({len(finite_wasserstein_distances)}/{len(wasserstein_distances)} ảnh): {mean_wasserstein_dist:.6f}")
else:
    print("\nKhông thể tính toán Wasserstein Distance cho bất kỳ ảnh nào.")

y_pred = model.predict(X_test)
y_pred = np.squeeze(y_pred)

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def describe_Image(image):
    df = pd.DataFrame(np.squeeze(image).flatten()).describe()
    return df[0].to_dict()

# Giả định y_test và y_pred đã được định nghĩa từ trước
# Ví dụ:
# y_test = [np.random.rand(100) * i for i in range(1, 101)]
# y_pred = [x + np.random.randn(100) * 0.1 * i/100 for i, x in enumerate(y_test)]

# Chuyển đổi y_test và y_pred sang numpy array nếu chưa phải
y_test = np.array(y_test)
y_pred = np.array(y_pred)

max_values_y_test = np.array([np.max(x) for x in y_test])
sort_indices = np.argsort(max_values_y_test)

y_test_sorted = y_test[sort_indices]
y_pre_sorted = y_pred[sort_indices]

_median = [np.median(x) for x in y_test_sorted]
_median_pre = [np.median(x) for x in y_pre_sorted]
y_des = [describe_Image(x) for x in y_test_sorted]
y_des_pre = [describe_Image(x) for x in y_pre_sorted]

# --- Phần mới: Loại bỏ các dự đoán khác xa thực tế ---
# Xác định ngưỡng khác biệt (có thể điều chỉnh)
# Ngưỡng này có thể là một phần trăm của giá trị max thực tế, hoặc một giá trị tuyệt đối
# Ví dụ: Loại bỏ nếu sự khác biệt MAX PREDICT và MAX lớn hơn 0.2
threshold = 0.1

filtered_y_test = []
filtered_y_pred = []
retained_indices = []

for i in range(len(y_test_sorted)):
    max_test = y_des[i]['max']
    max_pre = y_des_pre[i]['max']

    # Tính toán sự khác biệt tuyệt đối giữa giá trị max thực tế và max dự đoán
    diff_max = abs(max_test - max_pre)

    # Giữ lại nếu sự khác biệt nằm trong ngưỡng chấp nhận được
    if diff_max <= threshold:
        filtered_y_test.append(y_test_sorted[i])
        filtered_y_pred.append(y_pre_sorted[i])
        retained_indices.append(i) # Lưu lại chỉ số của các mẫu được giữ lại

# Chuyển đổi danh sách đã lọc thành numpy array
filtered_y_test = np.array(filtered_y_test)
filtered_y_pred = np.array(filtered_y_pred)

print(f"Số lượng mẫu ban đầu: {len(y_test_sorted)}")
print(f"Số lượng mẫu sau khi lọc: {len(filtered_y_test)}")

# Cập nhật các danh sách thống kê với dữ liệu đã lọc để vẽ biểu đồ
_median_filtered = [np.median(x) for x in filtered_y_test]
_median_pre_filtered = [np.median(x) for x in filtered_y_pred]
y_des_filtered = [describe_Image(x) for x in filtered_y_test]
y_des_pre_filtered = [describe_Image(x) for x in filtered_y_pred]

# --- Vẽ lại biểu đồ với dữ liệu đã lọc ---
plt.figure(figsize=(20, 10))

plt.plot(range(len(filtered_y_test)), _median_filtered, label='MEDIAN (Filtered)', color='red')
plt.plot(range(len(filtered_y_test)), _median_pre_filtered, label='MEDIAN PREDICT (Filtered)', color='green')

plt.plot(range(len(filtered_y_test)), [item['max'] for item in y_des_filtered], label='MAX (Filtered)', color='magenta')
plt.plot(range(len(filtered_y_test)), [item['max'] for item in y_des_pre_filtered], label='MAX PREDICT (Filtered)', color='black')

plt.plot(range(len(filtered_y_test)), [item['mean'] for item in y_des_filtered], label='MEAN (Filtered)', color='blue')
plt.plot(range(len(filtered_y_test)), [item['mean'] for item in y_des_pre_filtered], label='MEAN PREDICT (Filtered)', color='yellow')

plt.plot(range(len(filtered_y_test)), [item['min'] for item in y_des_filtered], label='MIN (Filtered)', color='black')
plt.plot(range(len(filtered_y_test)), [item['min'] for item in y_des_pre_filtered], label='MIN PREDICT (Filtered)', color='orange')

plt.title(f'Filter images with maximum depth difference threshold: 0.1 - From {len(y_test_sorted)} images to {len(filtered_y_test)} images')
plt.legend(loc='upper left')
plt.grid(True)
plt.show()

import tensorflow as tf
import numpy as np

# Đảm bảo y_test và y_pred có shape (N, H, W)
if y_test.ndim == 4 and y_test.shape[-1] == 1:
    y_test_ = np.squeeze(y_test, axis=-1)
else:
    y_test_ = y_test

if y_pred.ndim == 4 and y_pred.shape[-1] == 1:
    y_pred_ = np.squeeze(y_pred, axis=-1)
else:
    y_pred_ = y_pred

# Tính SSIM cho từng cặp ảnh
ssim_scores = []
for i in range(y_test.shape[0]):
    img_true = y_test[i]
    img_pred = y_pred[i]
    # Ensure shape is (H, W, 1) for tf.image.ssim
    if img_true.ndim == 2:
        img_true = np.expand_dims(img_true, axis=-1)
    if img_pred.ndim == 2:
        img_pred = np.expand_dims(img_pred, axis=-1)
    ssim_val = tf.image.ssim(img_true, img_pred, max_val=1.0).numpy()
    ssim_scores.append(ssim_val)
ssim_scores = np.array(ssim_scores)
mean_ssim = np.mean(ssim_scores)
mean_ssim_loss = 1.0 - mean_ssim

print(f"Trung bình SSIM: {mean_ssim:.4f}")
print(f"Trung bình sai số SSIM (1-SSIM): {mean_ssim_loss:.4f}")
# =========================

y_test = np.squeeze(y_test)
mse = np.mean((y_pred - y_test) ** 2)
print(f"Trung bình sai số MSE: {mse:.6f}")
# =========================

mae = tf.reduce_mean(np.abs(y_pred - y_test))
print(f"Trung bình sai số MAE: {mae}")
# =========================

# Tính RMSE cho từng cặp ảnh
rmse_list = [np.sqrt(np.mean((np.squeeze(y_test[i]) - np.squeeze(y_pred[i])) ** 2)) for i in range(y_test.shape[0])]
mean_rmse = np.mean(rmse_list)
print(f"Tổng trung bình sai số RMSE: {mean_rmse:.6f}")
# =========================