[
  {
    "path": ".gitignore",
    "content": "scala/target\nscala/project/target\nscala/project/project\nscala/.idea\n*.pyc\n.idea\ndist\nspark_ml_streaming.egg-info"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2015 Jeremy Freeman\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "[![Join the chat at https://gitter.im/freeman-lab/spark-ml-streaming](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/freeman-lab/spark-ml-streaming?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\n## Visualize streaming machine learning in Spark\n\n![two-dimensional-demo](https://github.com/freeman-lab/spark-streaming-demos/blob/master/animations/databricks-blog-post/4-five-clusters.gif)\n![one-dimensional-demo](https://github.com/freeman-lab/spark-streaming-demos/blob/master/animations/databricks-blog-post/6-half-life-5p0.gif)\n\n### About\nThis Python app generates data, analyzes it in Spark Streaming, and visualizes the results with Lightning. The analyses use streaming machine learning algorithms included with Spark as of version 1.2. The demos are designed for local use, but the same algorithms can run at scale on a cluster with millions of records.\n\n### How to use\nTo run these demos, you need:\n\n* A working installation of [Spark](http://spark.apache.org/downloads.html)\n* A running [Lightning](http://lightning-viz.org) server\n* An installation of Python with standard scientific computing libraries (NumPy, SciPy, ScikitLearn)\n\nWith those three things in place, install using:\n\n\tpip install spark-ml-streaming\n\nThen set `SPARK_HOME` to your Spark installation, and start an executable:\n\n\tstreaming-kmeans -l <lighting_host>\n\nWhere `lightning_host` is the address of your Lightning server. After it starts, your browser will open, and you should see data appear shortly. \n\nTry running with different settings, for example, to run a 1-d version with 4 clusters and a half-life of 10 points:\n\n\tstreaming-kmeans -p <temporary_path> -l <lighting_host> -nc 4 -nd 1 -hl 10 -tu points\n\nWhere `temporary_path` is where data will be written / read, if not specified the current tmp directory will be used (See Python [tempfile.gettempdir()](https://docs.python.org/2/library/tempfile.html))\n\n2D data will make a scatter plot and 1D data will make a line plot. You can set this with -nd.\n\nTo see all options type:\n\n\tstreaming-kmeans -h\n\n### Build\nThe demo relies on a Scala package included pre-built inside `python/mlstreaming/lib`. To rebuild it, use sbt:\n\n\tcd scala\n\tsbt package\n"
  },
  {
    "path": "python/MANIFEST.in",
    "content": "include *.txt\ninclude mlstreaming/lib/*.jar"
  },
  {
    "path": "python/bin/streaming-kmeans",
    "content": "#!/usr/bin/env python\n\nimport time\nimport subprocess\nimport argparse\nimport os\nimport tempfile\n\nfrom lightning import Lightning\n\nfrom mlstreaming import StreamingDemo\nfrom mlstreaming.util import findspark, findjar, baseargs\n\ndef main():\n\n    # parse arguments\n    parser = argparse.ArgumentParser(description='Streaming KMeans demo.')\n    parser = baseargs(parser)\n    parser.add_argument('-nc', '--ncenters', type=int, default=3, required=False, \n        help='Number of cluster centers')\n    parser.add_argument('-nd', '--ndims', type=int, default=2, required=False, \n        help='Number of dimensions')\n    parser.add_argument('-rs', '--randomseed', type=int, default=None, required=False,\n        help='Random seed')\n    parser.add_argument('-sd', '--std', type=float, default=0.3, required=False,\n        help='Standard deviation of points')\n    parser.add_argument('-up', '--update', type=str, choices=('jump', 'drift', 'none'), default='drift', required=False,\n        help='Update behavior')\n    parser.add_argument('-a', '--autoopen', type=bool, choices=(True, False), default=True, required=False,\n        help='Whether to automatically open Lightning session on a browser')\n    args = parser.parse_args()\n\n    # basic setup\n    sparkhome = findspark()\n    jar = findjar()\n    \n    # set up lightning\n    if args.lightning:\n        lgn = Lightning(args.lightning)\n        lgn.create_session('streaming-kmeans')\n        if (args.autoopen):\n            lgn.session.open()\n    else:\n        lgn = None\n\n    # set temp path\n    path = args.path\n    if not path or path == '':\n        path = tempfile.gettempdir()\n    tmpdir = os.path.join(path, 'streamkmeans')\n\n    # setup the demo\n    s = StreamingDemo.make('kmeans', npoints=args.npoints, nbatches=args.nbatches)\n    s.setup(tmpdir, overwrite=args.overwrite)\n    s.params(ncenters=args.ncenters, ndims=args.ndims, std=args.std, seed=args.randomseed, update=args.update)\n\n    # setup the spark job\n    sparkSubmit = sparkhome + \"/bin/spark-submit\"\n    sparkArgs = [\"--class\", \"spark.mlstreaming.KMeans\", jar]\n    demoArgs = [s.datain, s.dataout, str(args.batchtime), str(args.ncenters), str(args.ndims), str(args.halflife), str(args.timeunit)]\n    cmd = [sparkSubmit] + sparkArgs + demoArgs\n\n    try:\n        # start the spark job    \n        p = subprocess.Popen(cmd)\n        # wait for spark streaming to start up\n        time.sleep(4)\n        # start the demo\n        s.run(lgn)\n\n    finally:\n\n       p.kill()\n\nif __name__ == \"__main__\":\n    main()\n\n"
  },
  {
    "path": "python/mlstreaming/__init__.py",
    "content": "from mlstreaming.base import StreamingDemo\n\n__version__ = '0.1.0'"
  },
  {
    "path": "python/mlstreaming/base.py",
    "content": "import os\nimport shutil\n\n\nclass StreamingDemo(object):\n\n    def __init__(self, npoints=50, nbatches=5):\n        self.npoints = npoints\n        self.nbatches = nbatches\n\n    def params(*args, **kwargs):\n        \"\"\" Get analysis-specific parameters \"\"\"\n        raise NotImplementedError\n\n    def run(*args, **kwargs):\n        \"\"\" Run the streaming demo \"\"\"\n        raise NotImplementedError\n\n    @staticmethod\n    def make(demoname, *args, **kwargs):\n        \"\"\" Create a streaming demo \"\"\"\n\n        from mlstreaming.kmeans import StreamingKMeans\n\n        DEMOS = {\n            'kmeans': StreamingKMeans\n        }\n        return DEMOS[demoname](*args, **kwargs)\n\n    def setup(self, path, overwrite=False):\n        \"\"\" Setup paths for a streaming demo where temporary data will be read / written\"\"\"\n\n        if os.path.isdir(path):\n            if overwrite:\n                shutil.rmtree(path)\n                os.mkdir(path)\n            else:\n                raise Exception('Base directory %s already exists and overwrite is set to False' % path)\n        else:\n            os.mkdir(path)\n\n        datain = os.path.join(path, 'input')\n        dataout = os.path.join(path, 'output')\n        if os.path.isdir(datain):\n            shutil.rmtree(datain)\n        if os.path.isdir(dataout):\n            shutil.rmtree(dataout)\n        os.mkdir(datain)\n        os.mkdir(dataout)\n        self.datain = datain\n        self.dataout = dataout\n        return self\n\n    def writepoints(self, pts, i):\n        \"\"\" Write data points in a form that can be read by MLlib's vector parser  \"\"\"\n\n        f = file(os.path.join(self.datain, 'batch%g.txt' % i), 'w')\n        s = map(lambda p: \",\".join(str(p).split()).replace('[,', '[').replace(',]', ']'), pts)\n        tmp = \"\\n\".join(s)\n        f.write(tmp)\n        f.close()\n\n"
  },
  {
    "path": "python/mlstreaming/kmeans.py",
    "content": "import time\n\nfrom numpy import asarray, array, vstack, hstack, size, random, argsort, ones, argmin, sin, cos, pi\nfrom scipy.spatial.distance import cdist\nfrom sklearn.datasets import make_blobs\n\nfrom mlstreaming.base import StreamingDemo\nfrom mlstreaming.util import loadrecent\n\n\nclass StreamingKMeans(StreamingDemo):\n\n    def params(self, ncenters=3, ndims=2, std=0.2, seed=None, update='drift', interval=15, transition=None):\n        \"\"\"\n        Set up parameters for a streaming kmeans algorithm demo.\n\n        Parameters\n        ----------\n        ncenters : int, or array-like (ncenters, ndims)\n          Number of clusters as an integer, or an array of starting cluster centers.\n          If given as an integer, cluster centers will be determined randomly.\n\n        ndims : int\n          Number of dimensions\n\n        std : scalar\n          Cluster standard deviation\n\n        \"\"\"\n\n        random.seed(seed)\n        if size(ncenters) == 1:\n            centers = random.randn(ncenters, ndims) * 2\n        else:\n            centers = asarray(ncenters)\n            ncenters = centers.shape[0]\n        self.centers = centers\n        self.ncenters = ncenters\n        self.ndims = ndims\n        self.std = std\n        self.update = update\n        self.interval = interval\n        self.transition = transition\n\n        return self\n\n    def run(self, lgn=None):\n\n        viz = None\n\n        closestpoint = lambda centers, p: argmin(cdist(centers, array([p])))\n\n        centers = self.centers\n        modeltime = 0\n        model = []\n\n        # loop over batches\n        for i in range(1, self.nbatches):\n\n            print('generating batch %g' % i)\n\n            # drift means the points will slowly drift by adding noise to the position\n            if self.update == 'drift':\n                centers += random.randn(centers.shape[0], centers.shape[1]) * 0.15\n\n            # jump means every 15 batches the points will shift\n            if self.update == 'jump':\n                if i % self.interval == 0:\n                    if self.transition:\n                        centers = asarray(self.transition)\n                    else:\n                        base = random.rand(self.ncenters * self.ndims) * 1 + 2\n                        delta = asarray([-d if random.rand() > 0.5 else d for d in base])\\\n                            .reshape(self.ncenters, self.ndims)\n                        centers = centers + delta\n\n            # generate the points by sampling from the clusters and write to disk\n            npoints = self.npoints\n            pts, labels = make_blobs(npoints, self.ndims, centers, cluster_std=self.std)\n            self.writepoints(pts, i)\n            time.sleep(1)\n\n            # get the latest model (after waiting)\n            model, modeltime = loadrecent(self.dataout + '/*-model.txt', modeltime, model)\n\n            # plot an update (if we got a valid model)\n            if len(model) == self.ncenters:\n\n                clrs = labels\n                order = argsort(labels)\n                clrs = clrs[order]\n                pts = pts[order]\n                s = ones(self.npoints) * 10\n\n                if self.ndims == 1:\n                    pts = vstack((pts, model[:,None]))\n                else:\n                    pts = vstack((pts, model))\n                clrs = hstack((clrs, ones(self.ncenters) * 5))\n                s = hstack((s, ones(self.ncenters) * 10))\n\n                # wait a few iterations before plotting\n                if (lgn is not None) & (i > 5):\n\n                    # scatter plot for two dimensions\n                    if self.ndims == 2:\n                        if viz is None:\n                            viz = lgn.scatterstreaming(pts[:, 0], pts[:, 1], label=clrs, size=s)\n                        else:\n                            viz.append(pts[:, 0], pts[:, 1], label=clrs, size=s)\n\n                    # line plot for one dimension\n                    elif self.ndims == 1:\n                        if viz is None:\n                            viz = lgn.linestreaming(pts, label=clrs, size=s/2)\n                        else:\n                            viz.append(pts, label=clrs, size=s/2)\n\n                    else:\n                        raise Exception('Plotting only supported with 1 or 2 dimensions')\n"
  },
  {
    "path": "python/mlstreaming/lib/__init__.py",
    "content": ""
  },
  {
    "path": "python/mlstreaming/util.py",
    "content": "import os\nimport glob\n\nfrom numpy import loadtxt\n\n\ndef findspark():\n  \n    sparkhome = os.getenv(\"SPARK_HOME\")\n    if sparkhome is None:\n        raise Exception(\"The environment variable SPARK_HOME must be set to the Spark installation directory\")\n    else:\n        return sparkhome\n\n\ndef findjar():\n  \n    calldir = os.path.dirname(os.path.realpath(__file__))\n    jardir = os.path.join(calldir, 'lib', '*.jar')\n    jar = glob.glob(jardir)\n    if len(jar) == 0 or not os.path.exists(jar[0]):\n        raise Exception(\"Cannot find jar, looking at %s\" % jar)\n    else:\n        return jar[0]\n\n\ndef loadrecent(filename, oldtime, oldoutput):\n\n    try:\n        fname = max(glob.iglob(filename), key=os.path.getctime)\n    except:\n        print('No file found')\n        return [], oldtime\n\n    newtime = os.path.getctime(fname)\n    if not (newtime > oldtime):\n        print('File is not new')\n        return oldoutput, oldtime\n\n    try:\n        f = open(fname)\n        if os.fstat(f.fileno()).st_size == 0:\n            print('File is empty')\n            return [], oldtime\n    except:\n        print('Cannot load file')\n        return [], oldtime\n\n    prediction = loadtxt(fname, delimiter=',')\n    return prediction, newtime\n\n\ndef baseargs(parser):\n\n    parser.add_argument('-p', '--path', type=str, default=None, required=False,\n                        help='Temporary location to store outputs')\n    parser.add_argument('-o', '--overwrite', type=bool, choices=(True, False), default=True, required=False,\n                        help='Whether to overwrite the temporary location if it already exists')\n    parser.add_argument('-lgn', '--lightning', type=str, default=None, required=False,\n                        help='Lightning server for visualization')\n    parser.add_argument('-bt', '--batchtime', type=int, default=1, required=False,\n                        help='Frequency of updates')\n    parser.add_argument('-np', '--npoints', type=int, default=50, required=False,\n                        help='Number of data points per batch')\n    parser.add_argument('-nb', '--nbatches', type=int, default=40, required=False,\n                        help='Number of batches')\n    parser.add_argument('-hl', '--halflife', type=float, default=1, required=False,\n                        help='Half life for streaming updates')\n    parser.add_argument('-tu', '--timeunit', type=str, default='batches', choices=('batches', 'points'), required=False,\n                        help='Time unit for streaming updates')\n    return parser\n\n"
  },
  {
    "path": "python/requirements.txt",
    "content": "argparse\nnumpy\nscipy\nscikit-learn\nlightning-python"
  },
  {
    "path": "python/setup.py",
    "content": "#!/usr/bin/env python\n\nfrom setuptools import setup\nimport mlstreaming\n\nsetup(\n    name='spark-ml-streaming',\n    version=str(mlstreaming.__version__),\n    description='A Python library for visualizing streaming machine learning in Spark',\n    author='Jeremy Freeman',\n    author_email='the.freeman.lab@gmail.com',\n    url='https://github.com/freeman-lab/spark-ml-streaming',\n    packages=['mlstreaming',\n              'mlstreaming.lib'\n              ],\n    scripts = ['bin/streaming-kmeans'],\n    package_data = {'mlstreaming.lib': ['spark-ml-streaming_2.10-' + str(mlstreaming.__version__) + '.jar']},\n    install_requires=open('requirements.txt').read().split()\n)"
  },
  {
    "path": "scala/build.sbt",
    "content": "name := \"spark-ml-streaming\"\n\nversion := \"0.1.0\"\n\nscalaVersion := \"2.10.3\"\n\nivyXML := <dependency org=\"org.eclipse.jetty.orbit\" name=\"javax.servlet\" rev=\"3.0.0.v201112011016\">\n<artifact name=\"javax.servlet\" type=\"orbit\" ext=\"jar\"/>\n</dependency>\n\nlibraryDependencies += \"org.apache.hadoop\" % \"hadoop-client\" % \"1.0.4\"\n\nlibraryDependencies += \"org.apache.spark\" %% \"spark-core\" % \"1.2.0\" \n\nlibraryDependencies += \"org.apache.spark\" %% \"spark-streaming\" % \"1.2.0\" \n\nlibraryDependencies += \"org.apache.spark\" % \"spark-mllib_2.10\" % \"1.2.0\"\n\nlibraryDependencies += \"org.scalatest\" % \"scalatest_2.10\" % \"2.0\" % \"test\"\n\nlibraryDependencies += \"io.spray\" %% \"spray-json\" % \"1.2.5\"\n\nlibraryDependencies += \"org.jblas\" % \"jblas\" % \"1.2.3\"\n\nresolvers += \"spray\" at \"http://repo.spray.io/\"\n\nresolvers ++= Seq(\n  \"Akka Repository\" at \"http://repo.akka.io/releases/\",\n  \"Spray Repository\" at \"http://repo.spray.cc/\")\n"
  },
  {
    "path": "scala/project/build.properties",
    "content": "sbt.version=0.12.4\n"
  },
  {
    "path": "scala/src/main/scala/spark/mlstreaming/KMeans.scala",
    "content": "package spark.mlstreaming\n\nimport java.util.Calendar\n\nimport org.apache.spark.SparkConf\nimport org.apache.spark.mllib.clustering.StreamingKMeans\nimport org.apache.spark.mllib.linalg.Vectors\nimport org.apache.spark.streaming.{Seconds, StreamingContext}\n\n\n/**\n * Demo of streaming k-means with Spark Streaming.\n * Reads data from one directory, and prints models and predictions to another.\n *\n * Run via Python executable in the top-level project directory\n *\n */\n\nobject KMeans {\n\n  def main(args: Array[String]) {\n    if (args.length != 7) {\n      System.err.println(\n        \"Usage: KMeans \" +\n          \"<inputDir> <outputDir> <batchDuration> <numClusters> <numDimensions> <halfLife> <batchUnit>\")\n      System.exit(1)\n    }\n\n    val (inputDir, outputDir, batchDuration, numClusters, numDimensions, halfLife, timeUnit) =\n      (args(0), args(1), args(2).toLong, args(3).toInt, args(4).toInt, args(5).toFloat, args(6))\n\n    val conf = new SparkConf().setMaster(\"local\").setAppName(\"KMeansDemo\")\n    val ssc = new StreamingContext(conf, Seconds(batchDuration))\n\n    val trainingData = ssc.textFileStream(inputDir).map(Vectors.parse)\n\n    val model = new StreamingKMeans()\n      .setK(numClusters)\n      .setHalfLife(halfLife, timeUnit)\n      .setRandomCenters(numDimensions, 0.0)\n\n    model.trainOn(trainingData)\n\n    val predictions = model.predictOn(trainingData)\n\n    predictions.foreachRDD { rdd =>\n      val modelString = model.latestModel().clusterCenters\n        .map(c => c.toString.slice(1, c.toString.length-1)).mkString(\"\\n\")\n      val predictString = rdd.map(p => p.toString).collect().mkString(\"\\n\")\n      val dateString = Calendar.getInstance().getTime.toString.replace(\" \", \"-\").replace(\":\", \"-\")\n      Utils.printToFile(outputDir, dateString + \"-model\", modelString)\n      Utils.printToFile(outputDir, dateString + \"-predictions\", predictString)\n    }\n\n    ssc.start()\n    ssc.awaitTermination()\n  }\n}\n"
  },
  {
    "path": "scala/src/main/scala/spark/mlstreaming/Utils.scala",
    "content": "package spark.mlstreaming\n\nimport java.io.{FileWriter, BufferedWriter, File}\n\n/**\n * Utilities for streaming demos\n */\n\nobject Utils {\n\n  def printToFile(pathName: String, fileName: String, contents: String) = {\n    val file = new File(pathName + \"/\" + fileName + \".txt\")\n    val bw = new BufferedWriter(new FileWriter(file))\n    bw.write(contents)\n    bw.close()\n  }\n\n\n}\n"
  }
]