{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "esra00",
   "metadata": {},
   "source": [
    "# Loading a SOM exported from ESRA\n",
    "\n",
    "ESRA (Ethnographic Sound Recordings Archive) can export every trained\n",
    "self-organizing map with **⬇ SOM exportieren** on the analysis page. The\n",
    "download is a `.zip` with\n",
    "\n",
    "* `som.npz` – the arrays: `weights` (units × features), `codebook`\n",
    "  (rows × cols × features), `umatrix`, `recording_id`, `bmu`, `bmu_row`,\n",
    "  `bmu_col`, `features`, `grid`, for timbre maps also `norm_mean`/`norm_std`\n",
    "  (z-score) and the input vectors `data` / `data_z`,\n",
    "* `som.json` – kind of map, algorithm and parameters, normalisation, ESRA\n",
    "  version, export date and the metadata of every piece,\n",
    "* `README.txt`.\n",
    "\n",
    "This notebook loads such a file and shows the U-matrix, the pieces on the map\n",
    "coloured by a metadata field, and the component planes. It uses the plotting\n",
    "helpers of `comsar` where they exist and plain matplotlib otherwise.\n",
    "Unit `u` of the map sits at `row = u // cols`, `col = u % cols`; row 0 is\n",
    "drawn at the top, as in ESRA."
   ]
  },
  {
   "cell_type": "code",
   "id": "esra01",
   "metadata": {},
   "source": [
    "from pathlib import Path\n",
    "import io, json, zipfile\n",
    "\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "try:\n",
    "    from comsar.tracks.helpers import plot_umatrix  # comsar's style for the U-matrix\n",
    "except ImportError:\n",
    "    plot_umatrix = None\n",
    "\n",
    "# Path of the downloaded export\n",
    "EXPORT = Path('ESRA_archiv_som_1.zip')   # file name of your download"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "esra02",
   "metadata": {},
   "source": [
    "def load_esra_som(path):\n",
    "    \"\"\"Arrays (dict of numpy arrays) and description (dict) of an ESRA SOM export.\"\"\"\n",
    "    with zipfile.ZipFile(path) as zf:\n",
    "        with np.load(io.BytesIO(zf.read('som.npz'))) as npz:\n",
    "            arrays = {k: npz[k] for k in npz.files}\n",
    "        desc = json.loads(zf.read('som.json'))\n",
    "    return arrays, desc\n",
    "\n",
    "A, D = load_esra_som(EXPORT)\n",
    "som = D['som']\n",
    "rows, cols = som['rows'], som['cols']\n",
    "print(f\"{D['collection']['name']}: {som['name']} ({som['kind_label']}, {rows} x {cols})\")\n",
    "print(f\"{len(D['pieces'])} pieces, {len(D['features'])} features, normalisation: {D['normalization']['method']}\")\n",
    "print('exported', D['exported'], 'with', D['esra_version'])\n",
    "print('arrays:', {k: v.shape for k, v in A.items()})"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "esra03",
   "metadata": {},
   "source": [
    "# Pieces as a table (pandas is optional)\n",
    "try:\n",
    "    import pandas as pd\n",
    "    pieces = pd.DataFrame(D['pieces'])\n",
    "    display(pieces.head())\n",
    "except ImportError:\n",
    "    pieces = D['pieces']\n",
    "    print(pieces[:3])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "esra04",
   "metadata": {},
   "source": [
    "## U-matrix\n",
    "\n",
    "Mean distance of every unit to its neighbours: dark ridges separate\n",
    "clusters."
   ]
  },
  {
   "cell_type": "code",
   "id": "esra05",
   "metadata": {},
   "source": [
    "def draw_umatrix(ax):\n",
    "    if 'umatrix' not in A:\n",
    "        ax.set_title('no U-matrix (legacy map)')\n",
    "        ax.set_xlim(-.5, cols - .5); ax.set_ylim(rows - .5, -.5)\n",
    "        return\n",
    "    if plot_umatrix is not None:\n",
    "        plot_umatrix(ax, A['umatrix'])\n",
    "        ax.invert_yaxis()   # comsar draws row 0 at the bottom, ESRA at the top\n",
    "    else:\n",
    "        ax.imshow(A['umatrix'], cmap='Greys', origin='upper')\n",
    "        ax.set_title('U-matrix')\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6, 6))\n",
    "draw_umatrix(ax)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "esra06",
   "metadata": {},
   "source": [
    "## Pieces on the map, coloured by a metadata field\n",
    "\n",
    "Set `FIELD` to any key of the pieces, e.g. `country`, `ethnic_group`,\n",
    "`style`, `origin`, `decade`, `tonal_system`."
   ]
  },
  {
   "cell_type": "code",
   "id": "esra07",
   "metadata": {},
   "source": [
    "FIELD = 'country'\n",
    "\n",
    "values = [p.get(FIELD) or '–' for p in D['pieces']]\n",
    "groups = sorted(set(values))\n",
    "colours = plt.cm.tab20(np.linspace(0, 1, max(len(groups), 2)))\n",
    "rng = np.random.default_rng(0)\n",
    "jitter = rng.uniform(-.3, .3, size=(len(values), 2))   # pieces on the same unit spread out\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8, 7))\n",
    "draw_umatrix(ax)\n",
    "for g, c in zip(groups, colours):\n",
    "    idx = [i for i, v in enumerate(values) if v == g]\n",
    "    ax.scatter(A['bmu_col'][idx] + jitter[idx, 0], A['bmu_row'][idx] + jitter[idx, 1],\n",
    "               s=40, color=c, edgecolor='k', linewidth=.4, label=f'{g} ({len(idx)})')\n",
    "ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', fontsize=8, title=FIELD)\n",
    "ax.set_title(f\"{som['name']}: pieces by {FIELD}\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "esra08",
   "metadata": {},
   "source": [
    "## Component planes\n",
    "\n",
    "The value of one feature over the whole map (the codebook column). For\n",
    "timbre maps the weights are z-scores; `DENORMALISE = True` shows them in the\n",
    "units of the feature again."
   ]
  },
  {
   "cell_type": "code",
   "id": "esra09",
   "metadata": {},
   "source": [
    "DENORMALISE = True\n",
    "N_PLANES = 12\n",
    "\n",
    "if 'codebook' not in A:\n",
    "    print('Legacy map without weights: no component planes.')\n",
    "else:\n",
    "    cb = A['codebook'].copy()\n",
    "    if DENORMALISE and 'norm_mean' in A:\n",
    "        cb = cb * A['norm_std'] + A['norm_mean']\n",
    "    names = list(A['features'])\n",
    "    n = min(N_PLANES, len(names))\n",
    "    ncol = min(4, n)\n",
    "    nrow = int(np.ceil(n / ncol))\n",
    "    fig, axs = plt.subplots(nrow, ncol, figsize=(3.2 * ncol, 3 * nrow), squeeze=False)\n",
    "    for k, ax in enumerate(axs.flat):\n",
    "        if k >= n:\n",
    "            ax.axis('off')\n",
    "            continue\n",
    "        im = ax.imshow(cb[:, :, k], cmap='inferno', origin='upper')\n",
    "        ax.set_title(names[k], fontsize=9)\n",
    "        ax.set_xticks([]); ax.set_yticks([])\n",
    "        fig.colorbar(im, ax=ax, fraction=.046)\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "esra10",
   "metadata": {},
   "source": [
    "## Placing a new piece on the map\n",
    "\n",
    "A new feature vector (same features, same order as `A['features']`) is\n",
    "normalised with the stored mean and standard deviation and assigned to the\n",
    "nearest unit. Here the first exported piece serves as an example."
   ]
  },
  {
   "cell_type": "code",
   "id": "esra11",
   "metadata": {},
   "source": [
    "if 'weights' in A and 'data' in A:\n",
    "    x = A['data'][0]\n",
    "    if 'norm_mean' in A:\n",
    "        x = (x - A['norm_mean']) / A['norm_std']\n",
    "    unit = int(np.argmin(np.nansum((A['weights'] - x) ** 2, axis=1)))\n",
    "    print('best matching unit', unit, '-> row', unit // cols, 'col', unit % cols,\n",
    "          '| stored:', int(A['bmu'][0]))"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
