{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Basic usage"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Go to:\n",
    "    \n",
    "  - [Notebook configuration](basic_usage.ipynb#Notebook-configuration)\n",
    "  - [Getting started](basic_usage.ipynb#Getting-started)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Notebook configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.523135Z",
     "start_time": "2021-10-01T09:13:26.427353Z"
    }
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "# Optional dependencies\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import cnnclustering\n",
    "from cnnclustering import cluster"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Print Python and package version information:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.530534Z",
     "start_time": "2021-10-01T09:13:28.525553Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python:  3.8.8 (default, Mar 11 2021, 08:58:19)  [GCC 8.3.0]\n",
      "Packages:\n",
      "    matplotlib: 3.3.4\n",
      "    cnnclustering: 0.4.3\n"
     ]
    }
   ],
   "source": [
    "# Version information\n",
    "print(\"Python: \", *sys.version.split(\"\\n\"))\n",
    "\n",
    "print(\"Packages:\")\n",
    "for package in [mpl, cnnclustering]:\n",
    "    print(f\"    {package.__name__}: {package.__version__}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We use [Matplotlib](https://matplotlib.org/) to create plots. The `matplotlibrc` file in the root directory of the `CommonNNClustering` repository is used to customize the appearance of the plots."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.540353Z",
     "start_time": "2021-10-01T09:13:28.532580Z"
    }
   },
   "outputs": [],
   "source": [
    "# Matplotlib configuration\n",
    "mpl.rc_file(\n",
    "    \"../../matplotlibrc\",\n",
    "    use_default_template=False\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.547540Z",
     "start_time": "2021-10-01T09:13:28.542440Z"
    }
   },
   "outputs": [],
   "source": [
    "# Axis property defaults for the plots\n",
    "ax_props = {\n",
    "    \"aspect\": \"equal\"\n",
    "}\n",
    "\n",
    "# Property defaults for plotted lines\n",
    "dot_props = {\n",
    "    \"marker\": \"o\",\n",
    "    \"markeredgecolor\": \"k\"\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting started"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `cnnclustering.cluster` main module provides the `Clustering` class. An instance of this class is used to bundle input data (e.g. data points) with cluster results (cluster label assignments) alongside the clustering method (a fitter with a set of building blocks) and convenience functions for further analysis (not only in an Molecular Dynamics context). As a guiding principle, a `Clustering` object is always associated with one particular data set and allows varying cluster parameters."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "**Info:** The user is also refered to the [__scikit-learn-extra__ project](https://github.com/scikit-learn-contrib/scikit-learn-extra) for an alternative API following a parameter centered approach to clustering as `sklearn_extra.cluster.CommonNNClustering`.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `Clustering` can be initiated by passing *raw* input data to it. By default, this is expected to be a nested sequence, e.g. a list of lists. It will be understood as the coordinates of a number of data points in a feature space. Similar data structures, like a two-dimensional NumPy array would be acceptable, as well. It is possible to use different kinds of input data formats instead, like for example pre-computed pairwise distances, and it is described later how to do it (refer to tutorials [Clustering of scikit-learn toy data sets](scikit_learn_datasets.ipynb) and [Advanced usage](advanced_usage.ipynb))."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.559277Z",
     "start_time": "2021-10-01T09:13:28.549422Z"
    }
   },
   "outputs": [],
   "source": [
    "# 2D Data points (list of lists, 12 points in 2 dimensions)\n",
    "data_points = [   # Point index\n",
    "    [0, 0],       # 0\n",
    "    [1, 1],       # 1\n",
    "    [1, 0],       # 2\n",
    "    [0, -1],      # 3\n",
    "    [0.5, -0.5],  # 4\n",
    "    [2,  1.5],    # 5\n",
    "    [2.5, -0.5],  # 6\n",
    "    [4, 2],       # 7\n",
    "    [4.5, 2.5],   # 8\n",
    "    [5, -1],      # 9\n",
    "    [5.5, -0.5],  # 10\n",
    "    [5.5, -1.5],  # 11\n",
    "    ]\n",
    "\n",
    "clustering = cluster.Clustering(data_points)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can get a view of the input data associated with a `Clustering` back like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.574417Z",
     "start_time": "2021-10-01T09:13:28.561068Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0. ,  0. ],\n",
       "       [ 1. ,  1. ],\n",
       "       [ 1. ,  0. ],\n",
       "       [ 0. , -1. ],\n",
       "       [ 0.5, -0.5],\n",
       "       [ 2. ,  1.5],\n",
       "       [ 2.5, -0.5],\n",
       "       [ 4. ,  2. ],\n",
       "       [ 4.5,  2.5],\n",
       "       [ 5. , -1. ],\n",
       "       [ 5.5, -0.5],\n",
       "       [ 5.5, -1.5]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clustering.input_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "**Info:** The *raw* data points that we passed here to create the `Clustering` object are internally wrapped into a specific input data type and are stored on the instance under the `_input_data` attribute. `Clustering.input_data` is actually a shortcut for `Clustering._input_data.data`.  \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we cluster data points, we are essentially interested in cluster label assignments for these points. The labels will be exposed as `labels` attribute on the instance, which is currently `None` because no clustering has been done yet."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.583970Z",
     "start_time": "2021-10-01T09:13:28.576633Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clustering.labels is None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To cluster the points, we will use the `fit` method. The clustering depends on two parameters:\n",
    "  \n",
    "  - `radius_cutoff`: Points are considered neighbours if the distance between them is not larger than this cutoff radius $r$.\n",
    "  - `cnn_cutoff`: Points are assigned to the same cluster if they share at least this number of $c$ common neighbours.\n",
    "  \n",
    "For the clustering procedure, we ultimately need to compute the neighbouring points with respect to the `radius_cutoff` for each point in the data set. Then we can determine if two points fulfill the criterion of being part of the same cluster. How this is done, can be controlled in detail but by default the input data points are assumed to be given in euclidean space and the neighbours are computed brute force. For larger data sets, it makes sense to use a different approach."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.593066Z",
     "start_time": "2021-10-01T09:13:28.587006Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----------------------------------------------------------------------------------------------\n",
      "#points   r         c         min       max       #clusters %largest  %noise    time     \n",
      "12        2.000     1         None      None      2         0.583     0.167     00:00:0.000\n",
      "-----------------------------------------------------------------------------------------------\n",
      "\n"
     ]
    }
   ],
   "source": [
    "clustering.fit(radius_cutoff=2.0, cnn_cutoff=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A clustering attempt returns and prints a comprehensive record of the cluster parameters and the outcome. You can suppress the recording with the keyword argument `record=False` and the printing with `v=False`:\n",
    "\n",
    "  - **#points**: Number of data points in the data set.\n",
    "  - **r**: Radius cutoff *r*.\n",
    "  - **c**: Common-nearest-neighour cutoff *c*.\n",
    "  - **min**: Member cutoff (valid clusters need to have at least this many members).\n",
    "  - **max**: Maximum cluster count (keep only the *max* largest clusters and disregard smaller clusters).\n",
    "  - **#clusters**: Number of identified clusters.\n",
    "  - **%largest**: Member share on the total number of points in the largest cluster.\n",
    "  - **%noise**: Member share on the total number of points identified as noise (not part of any cluster).\n",
    "  \n",
    "The `min` (keyword argument `member_cutoff`) and `max` (keyword argument `max_clusters`) only take effect in an optional post processing step when `sort_by_size=True` (default). Then the clusters are sorted in order by there size, so that the first cluster (cluster 1) has the highest member count. Optionally, they are trimmed in the way that valid clusters have a minimum number of members (`member_cutoff`) and only the largest clusters are kept (`max_clusters`)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The outcome of the clustering are cluster label assignments for each point. Points classified as *noise* (not part of any cluster) are labeled 0. Integer labels larger than 0 indicate the membership of each point to one of the identified clusters. If clusters where sorted (`sort_by_size=True`), cluster 1 has the highest member count."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.602419Z",
     "start_time": "2021-10-01T09:13:28.595128Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clustering.labels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `labels` attribute of a cluster object always holds the result of the latest fit. All cluster results (from fits where `record=True`) are collected in a summary without storing the actual labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.612024Z",
     "start_time": "2021-10-01T09:13:28.604296Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----------------------------------------------------------------------------------------------\n",
      "#points   r         c         min       max       #clusters %largest  %noise    time     \n",
      "12        2.000     1         None      None      2         0.583     0.167     00:00:0.000\n",
      "-----------------------------------------------------------------------------------------------\n",
      "\n",
      "-----------------------------------------------------------------------------------------------\n",
      "#points   r         c         min       max       #clusters %largest  %noise    time     \n",
      "12        1.500     1         None      None      2         0.417     0.333     00:00:0.000\n",
      "-----------------------------------------------------------------------------------------------\n",
      "\n"
     ]
    }
   ],
   "source": [
    "clustering.fit(radius_cutoff=1.5, cnn_cutoff=1, v=False)\n",
    "print(*clustering.summary, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you have [Pandas](https://pandas.pydata.org/) installed, the summary can be transformed into a handy `pandas.DataFrame`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:28.638559Z",
     "start_time": "2021-10-01T09:13:28.614025Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n_points</th>\n",
       "      <th>radius_cutoff</th>\n",
       "      <th>cnn_cutoff</th>\n",
       "      <th>member_cutoff</th>\n",
       "      <th>max_clusters</th>\n",
       "      <th>n_clusters</th>\n",
       "      <th>ratio_largest</th>\n",
       "      <th>ratio_noise</th>\n",
       "      <th>execution_time</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>12</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1</td>\n",
       "      <td>&lt;NA&gt;</td>\n",
       "      <td>&lt;NA&gt;</td>\n",
       "      <td>2</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>0.166667</td>\n",
       "      <td>0.000038</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>12</td>\n",
       "      <td>1.5</td>\n",
       "      <td>1</td>\n",
       "      <td>&lt;NA&gt;</td>\n",
       "      <td>&lt;NA&gt;</td>\n",
       "      <td>2</td>\n",
       "      <td>0.416667</td>\n",
       "      <td>0.333333</td>\n",
       "      <td>0.000029</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   n_points  radius_cutoff  cnn_cutoff  member_cutoff  max_clusters  \\\n",
       "0        12            2.0           1           <NA>          <NA>   \n",
       "1        12            1.5           1           <NA>          <NA>   \n",
       "\n",
       "   n_clusters  ratio_largest  ratio_noise  execution_time  \n",
       "0           2       0.583333     0.166667        0.000038  \n",
       "1           2       0.416667     0.333333        0.000029  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clustering.summary.to_DataFrame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `Clustering` object comes with a variety of convenience methods that allow for example a quick look at a plot of data points and a cluster result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-10-01T09:13:29.230015Z",
     "start_time": "2021-10-01T09:13:28.640020Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 17200 characters]\n",
      "text/plain": [
       "<Figure size 750x450 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(1, 2)\n",
    "\n",
    "ax[0].set_title(\"original\")\n",
    "clustering.evaluate(\n",
    "    ax=ax[0], original=True,\n",
    "    ax_props=ax_props, plot_props=dot_props\n",
    "    )\n",
    "\n",
    "ax[1].set_title(\"clustered\")\n",
    "clustering.evaluate(\n",
    "    ax=ax[1],\n",
    "    ax_props=ax_props, plot_props=dot_props\n",
    "    )\n",
    "fig.tight_layout()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "cnnclustering38",
   "language": "python",
   "name": "cnnclustering38"
  },
  "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.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "164.988px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
