{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import os\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "\n",
    "# Better aesthetics - https://seaborn.pydata.org/tutorial/aesthetics.html\n",
    "sns.set_style(\"whitegrid\", {'axes.grid': False})\n",
    "sns.set_color_codes('dark')\n",
    "sns.set_context(\"paper\")\n",
    "sns.despine()\n",
    "\n",
    "\n",
    "import logging\n",
    "logging.getLogger().setLevel(logging.INFO)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def draw_feature_importance(feature_importance, cols):\n",
    "    \"\"\" Generate image from feature_importance\"\"\"\n",
    "\n",
    "    importance_df = pd.DataFrame({'features': cols, 'importance': feature_importance}).sort_values(by='importance',\n",
    "                                                                                           ascending=False)\n",
    "    fig, ax = plt.subplots()\n",
    "\n",
    "    sns.barplot(x='importance',\n",
    "                y='features',\n",
    "                data=importance_df,\n",
    "                label='Feature importance',\n",
    "                # color='b',\n",
    "                edgecolor='w'\n",
    "                )\n",
    "    ax.set_yticklabels(importance_df['features'], size=8)\n",
    "    return plt\n",
    "\n",
    "def plot_boxplot(X, client_id, algo, v):\n",
    "    \"\"\" Plotting 2d scatterplot. We arbitrarily take first two cols. \"\"\"\n",
    "    logging.info(\"Drawing boxplot\")\n",
    "    fig = plt.figure()\n",
    "    g = sns.boxplot(x=X.columns.tolist()[1],\n",
    "                    y=X.columns.tolist()[0],\n",
    "                    #size=X.columns.tolist()[2],\n",
    "                    #hue='cluster',\n",
    "                    data=X)\n",
    "    # TODO! get cluster value numbers, they are not shown atm\n",
    "    g.legend(loc='best', bbox_to_anchor=(1, 1), ncol=1)\n",
    "    plt.title(f\"Estimated number of clusters: {len(set(X['cluster']))}\")\n",
    "    current_path = os.path.dirname(__file__)\n",
    "    box_plot_location = f'{current_path}/resources/{algo}_clusters_boxplot_v{v}_{client_id}.png'\n",
    "    fig.savefig(box_plot_location, bbox_inches='tight')\n",
    "    return box_plot_location\n",
    "\n",
    "\n",
    "def plot_2d_scatter(X, client_id, algo, v):\n",
    "    \"\"\" Plotting 2d scatterplot. We arbitrarily take first two cols. \"\"\"\n",
    "    logging.info(\"Drawing 2d plot\")\n",
    "\n",
    "    fig = plt.figure()\n",
    "\n",
    "    g = sns.scatterplot(x=X.columns.tolist()[0],\n",
    "                        y=X.columns.tolist()[1],\n",
    "                        size=X.columns.tolist()[2],\n",
    "                        hue='cluster',\n",
    "                        palette=sns.color_palette('dark', n_colors=len(set(X['cluster']))),\n",
    "                        data=X)\n",
    "    # TODO! get cluster value numbers, they are not shown atm\n",
    "    g.legend(loc='best', bbox_to_anchor=(1.25, 1), ncol=1)\n",
    "    plt.title(f\"Estimated number of clusters: {len(set(X['cluster']))}\")\n",
    "    #current_path = os.path.dirname(__file__)\n",
    "    scatter_plot_location = f'{algo}_clusters_scatter_2d_v{v}_{client_id}.png'\n",
    "    fig.savefig(scatter_plot_location, bbox_inches='tight')\n",
    "    return scatter_plot_location\n",
    "\n",
    "\n",
    "def plot_3d_scatter(X, client_id, algo, v):\n",
    "    \"\"\" We plot a 3d cluster map, because we almost always have more than 2 clusters.\n",
    "     We arbitrarily take first 3 columns  \"\"\"\n",
    "    logging.info(\"Drawing 3d plot\")\n",
    "\n",
    "    fig = plt.figure()\n",
    "\n",
    "    ax = Axes3D(fig)\n",
    "    xs = X[X.columns[0]]\n",
    "    ys = X[X.columns[1]]\n",
    "    zs = X[X.columns[2]]\n",
    "    sns.set()\n",
    "    g = ax.scatter(xs, ys, zs,\n",
    "                   s=50,\n",
    "                   alpha=0.6,\n",
    "                   edgecolors='grey',\n",
    "                   c=X['cluster'].astype(np.float),  # TODO! change colors\n",
    "                   )\n",
    "    ax.legend(*g.legend_elements(),\n",
    "              loc=\"center left\",\n",
    "              title=\"Clusters\")\n",
    "\n",
    "    ax.set_xlabel(X.columns[0])\n",
    "    ax.set_ylabel(X.columns[1])\n",
    "    ax.set_zlabel(X.columns[2])\n",
    "    plt.title(f\"Estimated number of clusters: {len(set(X['cluster']))}\")\n",
    "    scatter_plot_location = f'{algo}_clusters_scatter_3d_v{v}_{client_id}.png'\n",
    "    fig.savefig(scatter_plot_location, bbox_inches='tight')\n",
    "    return scatter_plot_location"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pairplot(feature_vector, hue):\n",
    "    \n",
    "    df = feature_vector[feature_vector.columns.drop(list(feature_vector.filter(regex='_id')))]\n",
    "    \n",
    "    sns.pairplot(df,\n",
    "                 plot_kws={'alpha': 0.6, 's': 80, 'edgecolor': 'k'},\n",
    "                 diag_kind='kde',\n",
    "                 hue=hue\n",
    "                 )\n",
    "    return\n",
    "    \n",
    "    #plot_location = f'{current_path}/collection_pairplot_{collection_id}.png'\n",
    "    #plt.savefig(plot_location, bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_python3",
   "language": "python",
   "name": "conda_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.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
