{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Color Coding of Large Value Ranges"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data preprocessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The minimum value in the datatset is: 9.21257e-09\n",
      "The maximum value in the datatset is: 0.0040518567\n"
     ]
    }
   ],
   "source": [
    "##loading all relevant packages/libraries\n",
    "from netCDF4 import Dataset\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import numpy.ma as ma\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import cm\n",
    "import matplotlib.colors\n",
    "from matplotlib.colors import LinearSegmentedColormap\n",
    "import seaborn as sns\n",
    "from colormath.color_objects import LabColor\n",
    "from colormath.color_diff import delta_e_cie1994\n",
    "import colorsys\n",
    "import colorcet as cc\n",
    "import sys\n",
    "import os\n",
    "from lxml import etree\n",
    "\n",
    "##choosing the dataset depending on the date\n",
    "date = \"20210701\"\n",
    "\n",
    "data = Dataset(\"cloudnet_ice_water_content\\\\\"+date+\"_ny-alesund_iwc-Z-T-method.nc\")\n",
    "\n",
    "iwc = data.variables[\"iwc\"]\n",
    "iwc_data = np.transpose(iwc[:])\n",
    "\n",
    "##number of time-/height-steps\n",
    "time = np.size(iwc_data,1)\n",
    "height = np.size(iwc_data,0)\n",
    "\n",
    "##Max/Min\n",
    "iwc_max = np.amax(iwc_data)\n",
    "iwc_min = 1\n",
    "for x in range(0, height):\n",
    "    for y in range(0, time):\n",
    "        if((iwc_data[x,y] < iwc_min) and (iwc_data[x,y] > 0.0)):\n",
    "            iwc_min = iwc_data[x,y]\n",
    "\n",
    "print(\"The minimum value in the datatset is:\",iwc_min)\n",
    "print(\"The maximum value in the datatset is:\",iwc_max)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data histrogram and boxplot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The mean of the data is: 2.7695324674652626e-05\n",
      "The standard deviation of the data is: 0.000112096039369404\n",
      "The 0.25 % quantile is: 1.7802185254822689e-06\n",
      "The 0.75 % quantile is: 0.0001111541405407479\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Daniel Braun\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\numpy\\lib\\function_base.py:4650: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray.\n",
      "  arr.partition(\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 37684 characters]",
      "text/plain": [
       "<Figure size 1080x720 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "##mean and standard deviation\n",
    "mean = np.mean(iwc_data)\n",
    "print(\"The mean of the data is:\", mean)\n",
    "std = np.std(iwc_data)\n",
    "print(\"The standard deviation of the data is:\", std)\n",
    "\n",
    "iwc_flat = iwc_data.flatten()\n",
    "iwc_flat[iwc_flat == 0] = np.NaN\n",
    "iwc_flat = iwc_flat[~ np.isnan(iwc_flat)]\n",
    "\n",
    "##calculating quantiles\n",
    "quantil1 = 0.25\n",
    "quantil2 = 0.75\n",
    "quantile = np.quantile(iwc_flat, [quantil1, quantil2])\n",
    "print(\"The\", quantil1 ,\"% quantile is:\", quantile[0])\n",
    "print(\"The\", quantil2 ,\"% quantile is:\", quantile[1])\n",
    "\n",
    "##selecting bins for the histogram\n",
    "#bins = [10**-8, 10**-7, 10**-6, 10**-5, 10**-4, 10**-3, 10**-2]\n",
    "bins = np.logspace(-8, -2, 20)\n",
    "\n",
    "sns.set(style=\"ticks\")\n",
    "\n",
    "f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, \n",
    "                                    gridspec_kw={\"height_ratios\": (.15, .85)}, figsize=(15,10))\n",
    "\n",
    "\n",
    "##creating the plot\n",
    "sns.boxplot(x = iwc_flat, ax=ax_box)\n",
    "sns.histplot(iwc_flat, bins = bins, ax=ax_hist)\n",
    "\n",
    "ax_box.set(yticks=[])\n",
    "sns.despine(ax=ax_hist)\n",
    "sns.despine(ax=ax_box, left=True)\n",
    "\n",
    "ax_box.set_xscale(\"log\")\n",
    "ax_hist.set_xscale(\"log\")\n",
    "ax_box.set_xlim(10**-8, 10**-2)\n",
    "ax_hist.set_xlim(10**-8, 10**-2)\n",
    "ax_box.tick_params(axis='both', labelsize=20)\n",
    "ax_hist.tick_params(axis='both', labelsize=20)\n",
    "ax_hist.yaxis.label.set_size(20)\n",
    "ax_box.set_title(\"Boxplot - \"+date, fontsize = 25)\n",
    "ax_hist.set_title(\"Histogram - \"+date, fontsize = 25)\n",
    "\n",
    "#plt.savefig(\"Visualizations\\histogram_boxplot_\"+date+\".png\", format=\"png\", bbox_inches='tight')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Creation of the different color scales"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "### ColorCrafter\n",
    "\n",
    "rgb_list = list()\n",
    "\n",
    "##import csv-file\n",
    "map = pd.read_csv(\"Colormaps\\colorcrafter.csv\", delimiter = \";\")\n",
    "rgb_array = np.array(map[[\"R\", \"G\", \"B\"]])\n",
    "for values in rgb_array:\n",
    "    rgb_list.append(list(values))\n",
    "\n",
    "position_list = list(np.linspace(0, 1, 9))\n",
    "\n",
    "col_list = list()\n",
    "cdict = dict()\n",
    "\n",
    "##create a rgb-dict from the csv data\n",
    "for num, col in enumerate(['red', 'green', 'blue']):\n",
    "    col_list = [[position_list[i], rgb_list[i][num], rgb_list[i][num]] for i in range(len(position_list))]\n",
    "    cdict[col] = col_list\n",
    "\n",
    "##create the usable colormap\n",
    "colorcrafter_cm = cm.colors.LinearSegmentedColormap('colorcrafter_cm', segmentdata=cdict)\n",
    "\n",
    "\n",
    "### OMC / OMC_sl\n",
    "\n",
    "omc_maps = [\"omc\", \"omc_sl\"]\n",
    "\n",
    "for cmap in omc_maps:\n",
    "\n",
    "    ##import csv-file\n",
    "    map = pd.read_csv(\"Colormaps\\\\\" + cmap + \".csv\", delimiter = \";\")\n",
    "    rgb_array = np.array(map[[\"R\", \"G\", \"B\"]])\n",
    "    rgb_list = list()\n",
    "    for values in rgb_array:\n",
    "        rgb_list.append(list(values))\n",
    "\n",
    "    ##set positions\n",
    "    position_list_grey = list(np.linspace(0, 1/6, 3))\n",
    "    position_list_purple = list(np.linspace(1/6, 2/6, 3))\n",
    "    position_list_blue = list(np.linspace(2/6, 3/6, 3))\n",
    "    position_list_green = list(np.linspace(3/6, 4/6, 3))\n",
    "    position_list_yellow = list(np.linspace(4/6, 5/6, 3))\n",
    "    position_list_red = list(np.linspace(5/6, 1, 3))\n",
    "\n",
    "    psoition_list = list()\n",
    "    position_list = position_list_grey + position_list_purple + position_list_blue + position_list_green + position_list_yellow + position_list_red\n",
    "\n",
    "    col_list = list()\n",
    "    cdict = dict()\n",
    "\n",
    "    ##create a rgb-dict from the csv data\n",
    "    for num, col in enumerate(['red', 'green', 'blue']):\n",
    "        col_list = [[position_list[i], rgb_list[i][num], rgb_list[i][num]] for i in range(len(position_list))]\n",
    "        cdict[col] = col_list\n",
    "\n",
    "    ##create the usable linear segmented colormap\n",
    "    if(cmap == \"omc_sl\"):\n",
    "        omc_sl_cm = cm.colors.LinearSegmentedColormap('omc_sl_cm', segmentdata=cdict)\n",
    "    else: \n",
    "        omc_cm = cm.colors.LinearSegmentedColormap('omc_cm', segmentdata=cdict)\n",
    "\n",
    "\n",
    "### Data dependend (turbo as basis)\n",
    "\n",
    "rgb_list = list()\n",
    "\n",
    "turbo = cm.get_cmap('turbo', 12)\n",
    "cmap = turbo.colors\n",
    "for values in cmap:\n",
    "    rgb_list.append(list(values[:-1]))\n",
    "\n",
    "data_range = np.log(iwc_max) - np.log(iwc_min)\n",
    "quantile_range = [np.log(quantile[0]) - np.log(iwc_min), np.log(quantile[1]) - np.log(iwc_min)]\n",
    "quantile_percent = [quantile_range[0]/data_range, quantile_range[1]/data_range]\n",
    "\n",
    "##set coplor positions dependend on quantiles\n",
    "position_list1 = list(np.linspace(0, quantile_percent[0], 2))\n",
    "position_list2 = list(np.linspace(quantile_percent[0], quantile_percent[1], 10))\n",
    "position_list3 = list(np.linspace(quantile_percent[1], 1, 2))\n",
    "position_list = position_list1[:-1] + position_list2 + position_list3[-1:]\n",
    "\n",
    "col_list = list()\n",
    "cdict = dict()\n",
    "\n",
    "for num, col in enumerate(['red', 'green', 'blue']):\n",
    "    col_list = [[position_list[i], rgb_list[i][num], rgb_list[i][num]] for i in range(len(position_list))]\n",
    "    cdict[col] = col_list\n",
    "\n",
    "data_cm = cm.colors.LinearSegmentedColormap('data_cm', segmentdata=cdict)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Scatterplot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 725376 characters]",
      "text/plain": [
       "<Figure size 2160x720 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "###choose colormap you want to use:\n",
    "## Viridis: \"viridis\"\n",
    "## Rainbow: \"gist_rainbow_r\"\n",
    "## ColorCrafter: colorcrafter_cm\n",
    "## OMC: omc_cm\n",
    "## OMC_sl: omc_sl_cm\n",
    "## Turbo data dependend: data_cm\n",
    "colormap = omc_cm\n",
    "\n",
    "\n",
    "##creating grid\n",
    "x = np.arange(time)\n",
    "y = np.arange(height)\n",
    "x, y = np.meshgrid(x,y)\n",
    "\n",
    "##creating the scatterplot\n",
    "plt.figure(figsize=(30, 10))\n",
    "\n",
    "plt.scatter(\n",
    "    x = x,\n",
    "    y = y,\n",
    "    c = iwc_data[y,x],\n",
    "    s = 1,\n",
    "    linewidths = 0, \n",
    "    cmap = colormap,\n",
    "    norm = matplotlib.colors.LogNorm() ##logarithmic normalization\n",
    "    #marker = \",\"\n",
    ")\n",
    "\n",
    "matplotlib.pyplot.rc('axes', linewidth=2)\n",
    "plt.title('Ice water content - '+date, fontsize = 35)\n",
    "plt.xlabel('Time (UTC)', fontsize = 35)\n",
    "plt.ylabel('Height (km)', fontsize = 35)\n",
    "plt.yticks(list(range(0, height+2, int(height/12))), list(range(0, 13)), fontsize = 35)\n",
    "plt.xticks(list(range(0, time+2, int(time/6))), [\"00:00\", \"04:00\", \"08:00\", \"12:00\", \"16:00\", \"20:00\", \"00:00\"], fontsize = 35)\n",
    "plt.xlim([0, time+2])\n",
    "plt.ylim([0, height+2])\n",
    "cbar = plt.colorbar()\n",
    "cbar.set_label(label = \"$kg/m^3$\", fontsize = 35)\n",
    "for t in cbar.ax.get_yticklabels():\n",
    "     t.set_fontsize(35)\n",
    "plt.clim(10**-8, 10**-2)\n",
    "\n",
    "#plt.savefig(\"Visualizations\\scatter_OMC_\"+date+\".png\", format = \"png\", dpi = 300, bbox_inches='tight')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display of the color scale with its grayscale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAWMAAABxCAYAAAAAq8LFAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAEsklEQVR4nO3Wsa4bxxUG4KPgKogbF5HTCFARpGDgLkDK1EmAIIGgQkBSSL1fwE+QzqWcKi+Rx+Ez6AEMiTvnpNhd3iXFeyVCEnxgfx+w2JkzM8sld/ljHlRVBQA/ql/82DcAgDAGaEEYAzQgjAEaEMYADdxcu2C3232O+wD4Wdjv9xfrdsYADVy9M1795/vvYoyMHCOmkTHGiBwZI+f2NGVkZoxlbFrH1znTuG2PpT2NGJmRI2Naa2NEZkXmiMxc2hlV87Wq5tppP0/WVNVSy+Pa9Trv1kZ8+7c/xO9+8+XpeGZkzfd2umap1e28sV1zdtTZNXK5t5EZY7mnUbX8NhVZdRwby/cam1oezxXTZjwzY9qOV83PqSr+/q8/xj+/+VPENOYjM2Is7TEiRt6ep+lCf52zrpvu7+cUURmRYz7XWNpjUx+fZPzNF3+JN7/6c9TIqBxRmVFZm3ZGLOca2/E8mVNnc6LqbM3p8x3b57g8n9tntxnf1N43PteWfs3P8ddf/T7++o//Ht+h47u9fafytvbue1vH+x7r+Pl/Ya2NEaOW/12NGDnFqGn+X9WIrClGTsvYOM6Zx+ba3F9qOWLUdJx7vOay5pdf/za++vc3kW8z8lCRU0YeMsbb+ZxTzee1v9beZoy3Y24va/JNLu25Nt6s85faISMPaz5kZI6omo79qhGZ5/2xOeexX7VeZ2xqueTPbf+HH/53b6baGQM0IIwBGhDGAA0IY4AGhDFAA8IYoAFhDNCAMAZoQBgDNCCMARoQxgANCGOABoQxQAPCGKABYQzQgDAGaEAYAzQgjAEaEMYADQhjgAaEMUADwhigAWEM0IAwBmhAGAM0IIwBGhDGAA0IY4AGhDFAA8IYoIEHVVXXLNjtdp/rXgB+8vb7/cW6nTFAA1fvjAH49OyMARoQxgANCGOABoQxQAPCGKABYQzQgDAGaEAYAzQgjAEaEMYADQhjgAaEMUADwhigAWEM0IAwBmhAGAM0IIwBGhDGAA0IY4AGhDFAA8IYoAFhDNCAMAZo4ObaBbvd7nPcB8DPwn6/v1i3MwZo4Oqd8erVq1eRmTHGiDFGTNN00l+P89ran6bp4vj5nMw89jMzqupYW4/z2sfOef78eTx+/PjO8THGvevfN37XmvOx7XXeN37NNZ49exYvX768OP/S+vN7v/b7V1VUVUTEsX1X7Zr+2t7WHj58GDc3N+989vk9fsj5fWOXfoOPParq5Lls+1UVjx49iqdPn37wO3fpGvfN+djvdP45d32XS8eTJ0/ixYsXcTgcTjLicDgc29M0nRzntUv99RrbjFn7d+XCpXfmQ8YvvXNr7fXr1/dmqp0xQAPCGKABYQzQgDAGaEAYAzQgjAEaEMYADQhjgAaEMUADwhigAWEM0IAwBmhAGAM0IIwBGhDGAA0IY4AGhDFAA8IYoAFhDNCAMAZoQBgDNCCMARoQxgANCGOABoQxQAPCGKABYQzQgDAGaEAYAzQgjAEaEMYADTyoqrpmwW63+1z3AvCTt9/vL9btjAEauHpnDMCnZ2cM0IAwBmhAGAM0IIwBGhDGAA0IY4AGhDFAA8IYoAFhDNCAMAZoQBgDNPB/3i1pO5iX2NUAAAAASUVORK5CYII=",
      "text/plain": [
       "<Figure size 432x144 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "###choose colormap you want to analyse:\n",
    "## Viridis: \"viridis\"\n",
    "## Rainbow: \"gist_rainbow_r\"\n",
    "## ColorCrafter: colorcrafter_cm\n",
    "## OMC: omc_cm\n",
    "## OMC_sl: omc_sl_cm\n",
    "## Turbo data dependend: data_cm\n",
    "colormap = omc_cm\n",
    "\n",
    "\n",
    "##funtion to generate cmap-grayscale\n",
    "def grayscale_cmap(cmap):\n",
    "    cmap = plt.cm.get_cmap(cmap)\n",
    "    colors = cmap(np.arange(cmap.N))\n",
    "    RGB_weight = [0.299, 0.587, 0.114]\n",
    "    luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))\n",
    "    colors[:, :3] = luminance[:, np.newaxis]\n",
    "        \n",
    "    return LinearSegmentedColormap.from_list(cmap.name + \"_gray\", colors, cmap.N)\n",
    "    \n",
    "##function to plot cmap with its grayscale equivalent\n",
    "def view_colormap(cmap):\n",
    "    cmap = plt.cm.get_cmap(cmap)\n",
    "    colors = cmap(np.arange(cmap.N))\n",
    "    \n",
    "    cmap = grayscale_cmap(cmap)\n",
    "    grayscale = cmap(np.arange(cmap.N))\n",
    "    \n",
    "    fig, ax = plt.subplots(2, figsize=(6, 2),\n",
    "                           subplot_kw=dict(xticks=[], yticks=[]))\n",
    "    ax[0].imshow([colors], extent=[0, 10, 0, 1])\n",
    "    ax[1].imshow([grayscale], extent=[0, 10, 0, 1])\n",
    "\n",
    "view_colormap(colormap)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display of the color gradients"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x10da3246d40>"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 124344 characters]",
      "text/plain": [
       "<Figure size 936x576 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "###choose colormap you want to analyse:\n",
    "## Viridis: \"viridis\"\n",
    "## Rainbow: \"gist_rainbow_r\"\n",
    "## ColorCrafter: colorcrafter_cm\n",
    "## OMC: omc_cm\n",
    "## OMC_sl: omc_sl_cm\n",
    "## Turbo data dependend: data_cm\n",
    "colormap = omc_cm\n",
    "\n",
    "\n",
    "rgb = pd.DataFrame()\n",
    "hsv = pd.DataFrame()\n",
    "x = list()\n",
    "red = list()\n",
    "green = list()\n",
    "blue = list()\n",
    "h = list()\n",
    "s = list()\n",
    "v = list()\n",
    "\n",
    "##get color values of color scale\n",
    "cmap = cm.get_cmap(colormap)\n",
    "\n",
    "##create rgb- and hsv-arrays\n",
    "for i in range(0,101,1):\n",
    "    j = i/100\n",
    "    x.append(j)\n",
    "    red.append(cmap(j)[0])\n",
    "    green.append(cmap(j)[1])\n",
    "    blue.append(cmap(j)[2])\n",
    "    color_hsv = colorsys.rgb_to_hsv(cmap(j)[0], cmap(j)[1], cmap(j)[2])\n",
    "    h.append(color_hsv[0])\n",
    "    s.append(color_hsv[1])\n",
    "    v.append(color_hsv[2])\n",
    "\n",
    "rgb[\"x\"] = x\n",
    "rgb[\"red\"] = red\n",
    "rgb[\"green\"] = green\n",
    "rgb[\"blue\"] = blue\n",
    "\n",
    "hsv[\"x\"] = x\n",
    "hsv[\"h\"] = h\n",
    "hsv[\"s\"] = s\n",
    "hsv[\"v\"] = v\n",
    "\n",
    "##print the resulting line charts\n",
    "fig, (ax_rgb, ax_hsv) = plt.subplots(2, figsize=(13, 8))\n",
    "fig.subplots_adjust(hspace=0.4)\n",
    "rgb.plot.line(x = \"x\", y = [\"blue\", \"red\", \"green\"], ax = ax_rgb, linewidth = 2)\n",
    "hsv.plot.line(x = \"x\", y = [\"h\", \"s\", \"v\"], ax = ax_hsv, linewidth = 2)\n",
    "ax_rgb.set_title(\"RGB-gradient\", fontsize = 20)\n",
    "ax_hsv.set_title(\"HSV-gradient\", fontsize = 20)\n",
    "ax_rgb.set_xlabel(\"position in colormap\", fontsize = 12)\n",
    "ax_hsv.set_xlabel(\"position in colormap\", fontsize = 12)\n",
    "ax_rgb.set_ylabel(\"RGB-value\", fontsize = 12)\n",
    "ax_hsv.set_ylabel(\"HSV-value\", fontsize = 12)\n",
    "ax_rgb.set_xlim([0,1])\n",
    "ax_hsv.set_xlim([0,1])\n",
    "ax_rgb.set_ylim([0,1.01])\n",
    "ax_hsv.set_ylim([0,1.01])\n",
    "ax_rgb.tick_params(axis='both', labelsize=12)\n",
    "ax_hsv.tick_params(axis='both', labelsize=12)\n",
    "ax_rgb.legend(fontsize = 12)\n",
    "ax_hsv.legend(fontsize = 12)\n",
    "\n",
    "#plt.savefig(\"Visualizations\\gradient_viridis.png\", format = \"png\", dpi = 300, bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display of the color distances"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 51564 characters]",
      "text/plain": [
       "<Figure size 936x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "###choose colormap you want to analyse:\n",
    "## Viridis: \"viridis\"\n",
    "## Rainbow: \"gist_rainbow_r\"\n",
    "## ColorCrafter: colorcrafter_cm\n",
    "## OMC: omc_cm\n",
    "## OMC_sl: omc_sl_cm\n",
    "## Turbo data dependend: data_cm\n",
    "colormap = omc_cm\n",
    "\n",
    "\n",
    "##function to convert rgb to lab color\n",
    "def rgb2lab(inputColor):\n",
    "\n",
    "   num = 0\n",
    "   RGB = [0, 0, 0]\n",
    "\n",
    "   for value in inputColor :\n",
    "       value = float(value) / 255\n",
    "\n",
    "       if value > 0.04045 :\n",
    "           value = ( ( value + 0.055 ) / 1.055 ) ** 2.4\n",
    "       else :\n",
    "           value = value / 12.92\n",
    "\n",
    "       RGB[num] = value * 100\n",
    "       num = num + 1\n",
    "\n",
    "   XYZ = [0, 0, 0,]\n",
    "\n",
    "   X = RGB [0] * 0.4124 + RGB [1] * 0.3576 + RGB [2] * 0.1805\n",
    "   Y = RGB [0] * 0.2126 + RGB [1] * 0.7152 + RGB [2] * 0.0722\n",
    "   Z = RGB [0] * 0.0193 + RGB [1] * 0.1192 + RGB [2] * 0.9505\n",
    "   XYZ[ 0 ] = round( X, 4 )\n",
    "   XYZ[ 1 ] = round( Y, 4 )\n",
    "   XYZ[ 2 ] = round( Z, 4 )\n",
    "\n",
    "   XYZ[ 0 ] = float( XYZ[ 0 ] ) / 95.047         \n",
    "   XYZ[ 1 ] = float( XYZ[ 1 ] ) / 100.0          \n",
    "   XYZ[ 2 ] = float( XYZ[ 2 ] ) / 108.883      \n",
    "\n",
    "   num = 0\n",
    "   for value in XYZ :\n",
    "\n",
    "       if value > 0.008856 :\n",
    "           value = value ** ( 0.3333333333333333 )\n",
    "       else :\n",
    "           value = ( 7.787 * value ) + ( 16 / 116 )\n",
    "\n",
    "       XYZ[num] = value\n",
    "       num = num + 1\n",
    "\n",
    "   Lab = [0, 0, 0]\n",
    "\n",
    "   L = ( 116 * XYZ[ 1 ] ) - 16\n",
    "   a = 500 * ( XYZ[ 0 ] - XYZ[ 1 ] )\n",
    "   b = 200 * ( XYZ[ 1 ] - XYZ[ 2 ] )\n",
    "\n",
    "   Lab [ 0 ] = round( L, 4 )\n",
    "   Lab [ 1 ] = round( a, 4 )\n",
    "   Lab [ 2 ] = round( b, 4 )\n",
    "\n",
    "   return Lab\n",
    "\n",
    "##get values of the cmap\n",
    "cmap = cm.get_cmap(colormap)\n",
    "\n",
    "delta_e = pd.DataFrame()\n",
    "x = list()\n",
    "delta = list()\n",
    "\n",
    "##compare two adjacent colors and create resulting dataframe\n",
    "for i in range(0,100,1):\n",
    "    j = i/100\n",
    "    k = (i+1)/100\n",
    "    x.append(j)\n",
    "    color1_lab = rgb2lab([cmap(j)[0], cmap(j)[1], cmap(j)[2]])\n",
    "    color2_lab = rgb2lab([cmap(k)[0], cmap(k)[1], cmap(k)[2]])\n",
    "    color1 = LabColor(lab_l=color1_lab[0], lab_a=color1_lab[1], lab_b=color1_lab[2])\n",
    "    color2 = LabColor(lab_l=color2_lab[0], lab_a=color2_lab[1], lab_b=color2_lab[2])\n",
    "    delta.append(delta_e_cie1994(color1, color2))\n",
    "\n",
    "delta_e[\"x\"] = x\n",
    "delta_e[\"delta\"] = delta\n",
    "\n",
    "##plot the results\n",
    "fig, axs = plt.subplots(figsize=(13, 4))\n",
    "delta_e.plot.line(x = \"x\", y = \"delta\", ax = axs, linewidth = 2)\n",
    "axs.set_title(\"Color-Differences (Distances between two adjacent colors)\", fontsize = 20)\n",
    "axs.set_xlabel(\"position in colormap\", fontsize = 15)\n",
    "axs.set_ylabel(\"Delta_E-value\", fontsize = 15)\n",
    "axs.get_legend().remove()\n",
    "axs.tick_params(axis='both', labelsize=15)\n",
    "axs.set_xlim([0,1])\n",
    "axs.set_ylim([0,0.25])\n",
    "\n",
    "#plt.savefig(\"Visualizations\\delta_OMC.png\", format = \"png\", bbox_inches='tight', dpi = 300)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "b4afd9e7f00ff00d5904820210b2601581f57a689b87805264133ad9f1d9b34f"
  },
  "kernelspec": {
   "display_name": "Python 3.10.4 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  },
  "metadata": {
   "interpreter": {
    "hash": "67ff2b08a60b3c8d3383ece141b44d84ac527aa0fb2b4d51a958291ceaf46288"
   }
  },
  "orig_nbformat": 2
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
