# ======================================================================================
#
#     Rapid Deep Neural Networks
#
#     Licensed under the MIT License
# ______________________________________________________________________________________
# ......................................................................................

# Copyright (c) 2020-2025 Pantelis I. Kaplanoglou

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# .......................................................................................
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np

from pylab import *
from numpy import *
from matplotlib.colors import LinearSegmentedColormap
from PIL import Image

'''
class nlcmap(LinearSegmentedColormap):
  """A nonlinear colormap"""
  
  name = 'nlcmap'
  
  def __init__(self, cmap, levels):
    self.cmap = cmap
    self.monochrome = self.cmap.monochrome
    self.levels = asarray(levels, dtype='float64')
    self._x = self.levels - self.levels.min()
    self._x /= self._x.max()
    self._y = linspace(0, 1, len(self.levels))
  
  def __call__(self, xi, alpha=1.0, **kw):
    yi = interp(xi, self._x, self._y)
    return self.cmap(yi, alpha)
'''

class PlotConfusionMatrix(object):
  # --------------------------------------------------------------------------------------
  def __init__(self, confusion_matrix, title="Confusion Matrix"):
    self.confusion_matrix = confusion_matrix
    self.title = title
    
    base = [15 / 255.0, 25 / 255.0, 37 / 255.0]
    self.stars_cmap = LinearSegmentedColormap.from_list(
      "BlueGrayToWhite",
      [
        (0.0, tuple(base)),
        (0.1, tuple([np.minimum(x*5.5, 1.0) for x in base])),
        (0.3, tuple([np.minimum(x*6.8, 1.0) for x in base])),
        (0.6, tuple([np.minimum(x*7.5, 1.0) for x in base])),
        (1.0, (1.0, 1.0, 1.0))
      ]
    )
    self._is_stars = False
    self._cm_image = None
  
  # --------------------------------------------------------------------------------------
  def prepare(self, limit_classes=20, is_showing_stars=False, **kwargs):
    if not is_showing_stars:
      is_showing_stars = self.confusion_matrix.shape[0] > limit_classes
    
    if is_showing_stars:
      self.prepare_stars_image(**kwargs)
    else:
      self.prepare_text()
    return self
  # --------------------------------------------------------------------------------------
  def prepare_text(self):
    fig, ax = plt.subplots(figsize=(7.5, 7.5))
    ax.matshow(self.confusion_matrix, cmap=plt.cm.Blues, alpha=0.3)
    for i in range(self.confusion_matrix.shape[0]):
      for j in range(self.confusion_matrix.shape[1]):
        ax.text(x=j, y=i, s=self.confusion_matrix[i, j], va='center', ha='center', size='xx-large')

    plt.xlabel('Predicted Label', fontsize=18)
    plt.ylabel('Actual Label', fontsize=18)
    plt.title(self.title, fontsize=18)
  # --------------------------------------------------------------------------------------
  def prepare_stars_image(self, **kwargs):
    def normalize(x, c):
      nNormed = x.copy().astype(np.float32)
      for nClassIndex, nSampleCount in enumerate(c):
        if nSampleCount != 0:
          nNormed[nClassIndex, :] = nNormed[nClassIndex, :] / float(nSampleCount)
        else:
          nNormed[nClassIndex, :] = 0
      return nNormed
    
    fig, ax = plt.subplots(figsize=(9, 9))
    
    samples_per_class = np.sum(self.confusion_matrix, axis=1)
    cm_norm = normalize(self.confusion_matrix, samples_per_class)
    
    im = plt.imshow(cm_norm, cmap=self.stars_cmap, interpolation='none', vmin=0.0, vmax=1.0)
    if kwargs.get('has_colorbar', False):
      plt.colorbar(im)
    plt.xlabel('Predicted Label', fontsize=18)
    plt.ylabel('Actual Label', fontsize=18)
    plt.title(self.title, fontsize=18)

    self._is_stars = True
    nDim = self.confusion_matrix.shape[0]
    if nDim < 100:
      cm_norm = np.kron(cm_norm, np.ones((4, 4), dtype=cm_norm.dtype))
    elif nDim < 500:
      cm_norm = np.kron(cm_norm, np.ones((2, 2), dtype=cm_norm.dtype))
    cm_norm_color = (self.stars_cmap(cm_norm)*255.0).astype(np.uint8)
    self._cm_image = Image.fromarray(cm_norm_color, mode="RGBA")
  # --------------------------------------------------------------------------------------
  def save(self, filename, **kwargs):
    bIsUsingCMImage = self._is_stars and kwargs.get("is_cm_image", False)
    if bIsUsingCMImage:
      self._cm_image.save(filename, format="PNG")
    else:
      plt.savefig(filename, bbox_inches='tight')
    return self
  # --------------------------------------------------------------------------------------
  def show(self):
    plt.show()
  # --------------------------------------------------------------------------------------

