{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Towards a new (and pretty poor) compression scheme\n",
    "--------------------------------------------------\n",
    "\n",
    "I'm going to be working with some audio data for a while as I get prepared for a term project this semester. I'll be working (with a partner) to design a system for separating voices from music. Given my total lack of experience with [Digital Signal Processing][1] I figured that now was as good a time as ever to work on a couple of fun projects that would get me back up to speed.\n",
    "\n",
    "The first project I want to work on: Designing a new compression scheme for audio data.\n",
    "\n",
    "A Brief Introduction to Audio Compression\n",
    "-----------------------------------------\n",
    "\n",
    "Audio files when uncompressed (files ending with `.wav`) are huge. Like, 10.5 Megabytes per minute huge. Storage is cheap these days, but that's still an incredible amount of data that we don't really need. Instead, we'd like to compress that data so that it's not taking up so much space. There are broadly two ways to accomplish this:\n",
    "\n",
    "1. Lossless compression - Formats like [FLAC][2], [ALAC][3], and [Monkey's Audio (.ape)][4] all go down this route. The idea is that when you compress and uncompress a file, you get exactly the same as what you started with.\n",
    "\n",
    "2. Lossy compression - Formats like [MP3][5], [Ogg][6], and [AAC (`.m4a`)][7] are far more popular, but make a crucial tradeoff: We can reduce the file size even more during compression, but the decompressed file won't be the same.\n",
    "\n",
    "There is a fundamental tradeoff at stake: Using lossy compression sacrifices some of the integrity of the resulting file to save on storage space. Most people (I personally believe it's everybody) can't hear the difference, so this is an acceptable tradeoff. You have files that take up a 10<sup>th</sup> of the space, and nobody can tell there's a difference in audio quality.\n",
    "\n",
    "A PCA-based Compression Scheme\n",
    "------------------------------\n",
    "\n",
    "What I want to try out is a [PCA][8] approach to encoding audio. The PCA technique comes from Machine Learning, where it is used for a process called [Dimensionality Reduction][9]. Put simply, the idea is the same as lossy compression: if we can find a way that represents the data well enough, we can save on space. There are a lot of theoretical concerns that lead me to believe this compression style will not end well, but I'm interested to try it nonetheless.\n",
    "\n",
    "PCA works as follows: Given a dataset with a number of features, I find a way to approximate those original features using some \"new features\" that are statistically as close as possible to the original ones. This is comparable to a scheme like MP3: Given an original signal, I want to find a way of representing it that gets approximately close to what the original was. The difference is that PCA is designed for statistical data, and not signal data. But we won't let that stop us.\n",
    "\n",
    "The idea is as follows: Given a signal, reshape it into 1024 columns by however many rows are needed (zero-padded if necessary). Run the PCA algorithm, and do dimensionality reduction with a couple different settings. The number of components I choose determines the quality: If I use 1024 components, I will essentially be using the original signal. If I use a smaller number of components, I start losing some of the data that was in the original file. This will give me an idea of whether it's possible to actually build an encoding scheme off of this, or whether I'm wasting my time.\n",
    "\n",
    "Running the Algorithm\n",
    "---------------------\n",
    "\n",
    "The audio I will be using comes from the song [Tabulasa][10], by [Broke for Free][11]. I'll be loading in the audio signal to Python and using [Scikit-Learn][12] to actually run the PCA algorithm.\n",
    "\n",
    "We first need to convert the FLAC file I have to a WAV:\n",
    "\n",
    "[1]: https://en.wikipedia.org/wiki/Digital_signal_processing\n",
    "[2]: https://en.wikipedia.org/wiki/FLAC\n",
    "[3]: https://en.wikipedia.org/wiki/Apple_Lossless\n",
    "[4]: https://en.wikipedia.org/wiki/Monkey%27s_Audio\n",
    "[5]: https://en.wikipedia.org/wiki/MP3\n",
    "[6]: https://en.wikipedia.org/wiki/Vorbis\n",
    "[7]: https://en.wikipedia.org/wiki/Advanced_Audio_Coding\n",
    "[8]: https://en.wikipedia.org/wiki/Principal_component_analysis\n",
    "[9]: https://en.wikipedia.org/wiki/Dimensionality_reduction\n",
    "[10]: https://brokeforfree.bandcamp.com/track/tabulasa\n",
    "[11]: https://brokeforfree.bandcamp.com/album/xxvii\n",
    "[12]: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "!ffmpeg -hide_banner -loglevel panic -i \"Broke For Free/XXVII/01 Tabulasa.flac\" \"Tabulasa.wav\" -c wav"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, let's go ahead and load a small sample so you can hear what is going on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 1176060 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from IPython.display import Audio\n",
    "from scipy.io import wavfile\n",
    "\n",
    "samplerate, tabulasa = wavfile.read('Tabulasa.wav')\n",
    "\n",
    "start = samplerate * 14 # 10 seconds in\n",
    "end = start + samplerate * 10 # 5 second duration\n",
    "Audio(data=tabulasa[start:end, 0], rate=samplerate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we'll define the code we will be using to do PCA. It's very short, as the PCA algorithm is very simple."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "import numpy as np\n",
    "\n",
    "def pca_reduce(signal, n_components, block_size=1024):\n",
    "    \n",
    "    # First, zero-pad the signal so that it is divisible by the block_size\n",
    "    samples = len(signal)\n",
    "    hanging = block_size - np.mod(samples, block_size)\n",
    "    padded = np.lib.pad(signal, (0, hanging), 'constant', constant_values=0)\n",
    "    \n",
    "    # Reshape the signal to have 1024 dimensions\n",
    "    reshaped = padded.reshape((len(padded) // block_size, block_size))\n",
    "    \n",
    "    # Second, do the actual PCA process\n",
    "    pca = PCA(n_components=n_components)\n",
    "    pca.fit(reshaped)\n",
    "    \n",
    "    transformed = pca.transform(reshaped)\n",
    "    reconstructed = pca.inverse_transform(transformed).reshape((len(padded)))\n",
    "    return pca, transformed, reconstructed"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we've got our functions set up, let's try actually running something. First, we'll use `n_components == block_size`, which implies that we should end up with the same signal we started with."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 1176060 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabulasa_left = tabulasa[:,0]\n",
    "\n",
    "_, _, reconstructed = pca_reduce(tabulasa_left, 1024, 1024)\n",
    "\n",
    "Audio(data=reconstructed[start:end], rate=samplerate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "OK, that does indeed sound like what we originally had. Let's drastically cut down the number of components we're doing this with as a sanity check: the audio quality should become incredibly poor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 1176060 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_, _, reconstructed = pca_reduce(tabulasa_left, 32, 1024)\n",
    "\n",
    "Audio(data=reconstructed[start:end], rate=samplerate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, our reconstructed audio does sound incredibly poor! But there's something else very interesting going on here under the hood. Did you notice that the bassline comes across very well, but that there's no midrange or treble? The drums are almost entirely gone.\n",
    "\n",
    "[Drop the (Treble)][13]\n",
    "-----------------------\n",
    "\n",
    "It will help to understand PCA more fully when trying to read this part, but I'll do my best to break it down. PCA tries to find a way to best represent the dataset using \"components.\" Think of each \"component\" as containing some of the information you need in order to reconstruct the full audio. For example, you might have a \"low frequency\" component that contains all the information you need in order to hear the bassline. There might be other components that explain the high frequency things like singers, or melodies, that you also need.\n",
    "\n",
    "What makes PCA interesting is that it attempts to find the \"most important\" components in explaining the signal. In a signal processing world, this means that PCA is trying to find the signal amongst the noise in your data. In our case, this means that PCA, when forced to work with small numbers of components, will chuck out the noisy components first. It's doing it's best job to reconstruct the signal, but it has to make sacrifices somewhere.\n",
    "\n",
    "So I've mentioned that PCA identifies the \"noisy\" components in our dataset. This is equivalent to saying that PCA removes the \"high frequency\" components in this case: it's very easy to represent a low-frequency signal like a bassline. It's far more difficult to represent a high-frequency signal because it's changing all the time. When you force PCA to make a tradeoff by using a small number of components, the best it can hope to do is replicate the low-frequency sections and skip the high-frequency things.\n",
    "\n",
    "This is a very interesting insight, and it also has echos (pardon the pun) of how humans understand music in general. Other encoding schemes (like MP3, etc.) typically chop off a lot of the high-frequency range as well. There is typically a lot of high-frequency noise in audio that is nearly impossible to hear, so it's easy to remove it without anyone noticing. PCA ends up doing something similar, and while that certainly wasn't the intention, it is an interesting effect.\n",
    "\n",
    "## A More Realistic Example\n",
    "\n",
    "So we've seen the edge cases so far: Using a large number of components results in audio very close to the original, and using a small number of components acts as a low-pass filter. How about we develop something that sounds \"good enough\" in practice, that we can use as a benchmark for size? We'll use ourselves as judges of audio quality, and build another function to help us estimate how much space we need to store everything in.\n",
    "\n",
    "[13]: https://youtu.be/Ua0KpfJsxKo?t=1m17s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Raw</th>\n",
       "      <th>PCA</th>\n",
       "      <th>PCA w/ BZ2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>(1, 1)</th>\n",
       "      <td>69.054298</td>\n",
       "      <td>138.108597</td>\n",
       "      <td>16.431797</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(1, 2)</th>\n",
       "      <td>69.054306</td>\n",
       "      <td>69.054306</td>\n",
       "      <td>32.981380</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(1, 4)</th>\n",
       "      <td>69.054321</td>\n",
       "      <td>34.527161</td>\n",
       "      <td>16.715032</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(4, 32)</th>\n",
       "      <td>69.054443</td>\n",
       "      <td>17.263611</td>\n",
       "      <td>8.481735</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(16, 256)</th>\n",
       "      <td>69.054688</td>\n",
       "      <td>8.631836</td>\n",
       "      <td>4.274846</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(32, 256)</th>\n",
       "      <td>69.054688</td>\n",
       "      <td>17.263672</td>\n",
       "      <td>8.542909</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(64, 256)</th>\n",
       "      <td>69.054688</td>\n",
       "      <td>34.527344</td>\n",
       "      <td>17.097543</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(128, 1024)</th>\n",
       "      <td>69.054688</td>\n",
       "      <td>17.263672</td>\n",
       "      <td>9.430644</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(256, 1024)</th>\n",
       "      <td>69.054688</td>\n",
       "      <td>34.527344</td>\n",
       "      <td>18.870387</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(512, 1024)</th>\n",
       "      <td>69.054688</td>\n",
       "      <td>69.054688</td>\n",
       "      <td>37.800940</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(128, 2048)</th>\n",
       "      <td>69.062500</td>\n",
       "      <td>8.632812</td>\n",
       "      <td>6.185015</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(256, 2048)</th>\n",
       "      <td>69.062500</td>\n",
       "      <td>17.265625</td>\n",
       "      <td>12.366942</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(512, 2048)</th>\n",
       "      <td>69.062500</td>\n",
       "      <td>34.531250</td>\n",
       "      <td>24.736506</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>(1024, 2048)</th>\n",
       "      <td>69.062500</td>\n",
       "      <td>69.062500</td>\n",
       "      <td>49.517493</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                    Raw         PCA  PCA w/ BZ2\n",
       "(1, 1)        69.054298  138.108597   16.431797\n",
       "(1, 2)        69.054306   69.054306   32.981380\n",
       "(1, 4)        69.054321   34.527161   16.715032\n",
       "(4, 32)       69.054443   17.263611    8.481735\n",
       "(16, 256)     69.054688    8.631836    4.274846\n",
       "(32, 256)     69.054688   17.263672    8.542909\n",
       "(64, 256)     69.054688   34.527344   17.097543\n",
       "(128, 1024)   69.054688   17.263672    9.430644\n",
       "(256, 1024)   69.054688   34.527344   18.870387\n",
       "(512, 1024)   69.054688   69.054688   37.800940\n",
       "(128, 2048)   69.062500    8.632812    6.185015\n",
       "(256, 2048)   69.062500   17.265625   12.366942\n",
       "(512, 2048)   69.062500   34.531250   24.736506\n",
       "(1024, 2048)  69.062500   69.062500   49.517493"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from bz2 import compress\n",
    "import pandas as pd\n",
    "\n",
    "def raw_estimate(transformed, pca):\n",
    "    # We assume that we'll be storing things as 16-bit WAV,\n",
    "    # meaning two bytes per sample\n",
    "    signal_bytes = transformed.tobytes()\n",
    "    # PCA stores the components as floating point, we'll assume\n",
    "    # that means 32-bit floats, so 4 bytes per element\n",
    "    component_bytes = transformed.tobytes()\n",
    "    \n",
    "    # Return a result in megabytes\n",
    "    return (len(signal_bytes) + len(component_bytes)) / (2**20)\n",
    "\n",
    "# Do an estimate for lossless compression applied on top of our\n",
    "# PCA reduction\n",
    "def bz2_estimate(transformed, pca):\n",
    "    bytestring = transformed.tobytes() + b';' + pca.components_.tobytes()\n",
    "    compressed = compress(bytestring)\n",
    "    return len(compressed) / (2**20)\n",
    "\n",
    "compression_attempts = [\n",
    "    (1, 1),\n",
    "    (1, 2),\n",
    "    (1, 4),\n",
    "    (4, 32),\n",
    "    (16, 256),\n",
    "    (32, 256),\n",
    "    (64, 256),\n",
    "    (128, 1024),\n",
    "    (256, 1024),\n",
    "    (512, 1024),\n",
    "    (128, 2048),\n",
    "    (256, 2048),\n",
    "    (512, 2048),\n",
    "    (1024, 2048)\n",
    "]\n",
    "\n",
    "def build_estimates(signal, n_components, block_size):\n",
    "    pca, transformed, recon = pca_reduce(tabulasa_left, n_components, block_size)\n",
    "    raw_pca_estimate = raw_estimate(transformed, pca)\n",
    "    bz2_pca_estimate = bz2_estimate(transformed, pca)\n",
    "    raw_size = len(recon.tobytes()) / (2**20)\n",
    "    return raw_size, raw_pca_estimate, bz2_pca_estimate\n",
    "\n",
    "pca_compression_results = pd.DataFrame([\n",
    "        build_estimates(tabulasa_left, n, bs)\n",
    "        for n, bs in compression_attempts\n",
    "    ])\n",
    "\n",
    "pca_compression_results.columns = [\"Raw\", \"PCA\", \"PCA w/ BZ2\"]\n",
    "pca_compression_results.index = compression_attempts\n",
    "pca_compression_results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, there are a couple of instances where we do nearly 20 times better on storage space than the uncompressed file. Let's here what that sounds like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 1176060 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_, _, reconstructed = pca_reduce(tabulasa_left, 16, 256)\n",
    "Audio(data=reconstructed[start:end], rate=samplerate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It sounds incredibly poor though. Let's try something that's a bit more realistic:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 1176060 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_, _, reconstructed = pca_reduce(tabulasa_left, 1, 4)\n",
    "Audio(data=reconstructed[start:end], rate=samplerate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And just out of curiosity, we can try something that has the same ratio of components to block size. This should be close to an apples-to-apples comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio controls=\"controls\" >\n",
       "                    <source src=\"data:audio/wav;base64,[encoded data, 1176060 characters]\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_, _, reconstructed = pca_reduce(tabulasa_left, 64, 256)\n",
    "Audio(data=reconstructed[start:end], rate=samplerate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The smaller block size definitely has better high-end response, but I personally think the larger block size sounds better overall."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusions\n",
    "\n",
    "So, what do I think about audio compression using PCA?\n",
    "\n",
    "Strangely enough, it actually works pretty well relative to what I expected. That said, it's a terrible idea in general.\n",
    "\n",
    "First off, you don't really save any space. The component matrix needed to actually run the PCA algorithm takes up a lot of space on its own, so it's very difficult to save space without sacrificing a huge amount of audio quality. And even then, codecs like AAC sound very nice even at bitrates that this PCA method could only dream of.\n",
    "\n",
    "Second, there's the issue of audio streaming. PCA relies on two components: the datastream, and a matrix used to reconstruct the original signal. While it is easy to stream the data, you can't stream that matrix. And even if you divided the stream up into small blocks to give you a small matrix, you must guarantee that the matrix arrives; if you don't have that matrix, the data stream will make no sense whatsoever.\n",
    "\n",
    "All said, this was an interesting experiment. It's really cool seeing PCA used for signal analysis where I haven't seen it applied before, but I don't think it will lead to any practical results. Look forward to more signal processing stuff in the future!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
