{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Interactive Computing in Scala with Jupyter and Almond\n", "\n", "*Note: This notebook has been originally written as the source of a [blog post about almond.](https://brunk.io/interactive-computing-in-scala-with-jupyter-and-almond.html)*\n", "\n", "The [Scala REPL](https://docs.scala-lang.org/overviews/repl/overview.html) is a great tool for trying out code interactively.\n", "It lets you write expressions in a terminal window, and immediately prints the return value as well as any outputs to the console.\n", "Whether you're learning the language, exploring an API, or sketching out a new idea, the immediate feedback after evaluating an expression is a great enabler for hands-on learning and rapid prototyping. \n", "\n", "The easiest way to get started is the default REPL because it's part of the Scala distribution and is also available in any SBT project as the `console` command.\n", "The default REPL lacks many convenience features though." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ammonite\n", "\n", "[Ammonite](http://ammonite.io/#Ammonite-REPL) is a modern REPL implementation created by Li Haoyi. It comes with many features that make working in the REPL more convenient. Probably the most important one is dynamic maven dependency loading in the REPL itself (through [Coursier](https://coursier.github.io/coursier/snapshot/docs/intro)), which allows you to import and immediately use almost any published Scala or Java library. It also has many others convenience features, such as\n", "* multi line editing support\n", "* better syntax highlighting. i.e. inputs are highlighted as you type\n", "* much better autocompletion\n", "* pretty printed, nicely formatted outputs\n", "* undo/redo, session handling and more\n", "\n", "If you know Python, Ammonite (roughly) is to the default Scala REPL what the [IPython](https://ipython.org/) shell is to the default Python shell. Parts of Ammonite are also used in the default dotty REPL, which means they will be available in Scala 3.\n", "\n", "While Ammonite has many improvements compared to the default REPL, the basic execution model is still the same.\n", "You enter an expression (or multiple expressions in a block). You press enter to have it evaluated to immediately see the output below your input. You then repeat with a new expression or by refining the previous one and executing it again. As a result, your inputs are interleaved with the computed output values.\n", "\n", "\"Ammonite\"\n", "

The Ammonite REPL (Source: ammonite.io)

\n", "\n", "This model of interaction helps you to iterate fast due to the immediate feedback, but it also has some drawbacks:\n", "* Seeing multiple inputs at once can be hard, because they are interleaved with their outputs, especially if the outputs are long.\n", "* It also makes it harder to copy multiple consecutive inputs into an editor.\n", "* Finding and changing older inputs often means scrolling back or searching the history because they are far away or in the console window completely gone due to newer outputs.\n", "* Selectively replaying multiple expressions after changes in an earlier input or after a REPL restart can be tedious.\n", "\n", "You can show the history of inputs using `:history` in the default REPL or `repl.history` in Ammonite. While the history can be helpful, it is often cluttered with refinement attempts, which you still need to filter out.\n", "\n", "An interesting REPL variant that addresses some of these issues are worksheets." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Worksheets\n", "\n", "From the Dotty documentation:\n", "\n", "> A worksheet is a Scala file that is evaluated on save, and the result of each expression is shown in a column to the right of your program. Worksheets are like a REPL session on steroids, and enjoy 1st class editor support: completion, hyperlinking, interactive errors-as-you-type, etc.\n", "\n", "\"Worksheet\n", "\n", "

Worksheet example in Dotty IDE / Visual Studio Code. (source: Dotty documentation)

\n", "\n", "Let's go through this definition to explain how worksheets differ from the REPL:\n", "\n", "First of all, worksheets are files. That means we can put them under version control and share them with others more easily.\n", "\n", "Second, we enter our expressions into an editor window. In most cases, the input editor is on the left while the output is shown to the right. This layout makes it easier to see multiple expressions at once, because they are not interleaved with their outputs. It also makes it easier to write multi line expressions and to edit expressions.\n", "\n", "Third, a worksheet is evaluated on save. More specifically, **all** expressions are recomputed every time we save the worksheet. The advantage of this behaviour is that it's easy to change an earlier expression because all dependent values are automatically recomputed. The drawback is that you lose control over which expressions are evaluated so it's not very well suited for things that take longer than a few seconds like loading large datasets or running complex computations.\n", "\n", "The fourth point about editor support is mostly IDE dependent. Dotty IDE worksheet support looks very nice, but most of us are still stuck with Scala 2. I've tried IntelliJ worksheets a few times but they didn't work very well for me. Eclipse based Scala IDE had good worksheet support last time I tried it but isn't widely used for other reasons. There's also an online worksheet variant called [Scastie](https://scastie.scala-lang.org/) that only requires a browser and makes it very easy to share worksheets online.\n", "\n", "So worksheets solve some of the issues of REPLs mentioned above. Their layout and their execution model makes multiple expressions easier to read and to change, even if their outputs are shown. However, the execution model also introduces new issues.\n", "\n", "So the natural question that follows is: Could we combine the advantages of REPL and worksheets somehow? Interestingly, there is a technology that does have most of the advantages of both (and more): *Jupyter notebooks*." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter Notebooks\n", "\n", "[Jupyter notebooks](https://jupyter.org/) are interactive, web based documents that can contain executable code. Interactive notebooks are nothing new. In science, they're in use since the 80s and many different flavours exist.\n", "\n", "As of today though, Jupyter notebooks are by far the most successful and flexible variant. Some reasons for their success are that they're open-source, programming language agnostic, provide a modular architecture and a web-based frontend.\n", "That's why we will use Jupyter as an example to explain the basic concepts behind interactive notebooks. In fact, this article itself is written as a Jupyter notebook.\n", "\n", "A Jupyter notebook is made of editable input cells. Cells can be of different types. By default, two cell types are available:\n", "\n", "* **Documentation cells**, which are written in Markdown and rendered to HTML when we run them, using JavaScript directly in the browser. For instance, this text was written as a Markdown cell, and you see the HTML output.\n", "* **Code cells**, which allow you to write and execute code.\n", "\n", "Here's a simple example of a Scala code cell:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "println(\"Hello notebook!\")\n", "val x = 42" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Code cells are executed by so called **kernels**. A kernel is basically an interpreter process that executes the code of a code cell in the backend. Once you run a code cell, the frontend sends the current cell content to the kernel for processing. The kernel's output is then sent back to the frontend and written below the code cell. Later cells can access the variable state of previous cells as long as the kernel is still running." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x / 2 + 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jupyter Kernels can be implemented in any language as long as they follow the [ZeroMQ](http://zeromq.org/) based Jupyter communication protocol. IPython is the most popular kernel and is included by default. That's no surprise since Jupyter (**Ju**lia, **Pyt**hon, **R**) is derived from the IPython project. It is a result of separating the language independent part from the IPython kernel to make it work with other languages. Now there are kernels for over 100 programming languages available.\n", "\n", "\"Jupyter\n", "

High level overview of the Jupyter components (source: Jupyter documentation)

\n", "\n", "The Jupyter frontend renders the notebook and lets you interact with it. It provides editing capabilies, lets you create notebooks, execute cells and so on. The default frontend Jupyter classic is made of HTML & JavaScript and runs in the browser. In 2018, a modern, more flexible and modular frontend implementation called [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) was published as \"the next-generation web-based user interface for Project Jupyter\".\n", "\n", "\"JupyterLab\"\n", "

The JupyterLab interface (source: JupyterLab documentation)

\n", "\n", "The modular architecture of Jupyter allows you to run kernels anywhere: On your laptop, in the cloud, or on a powerful GPU machine for deep learning.\n", "The frontend on the other hand, even runs on a tablet. You only need a modern web-browser.\n", "\n", "There are also desktop frontends with additional features like [nteract](https://nteract.io/).\n", "A large ecosystem around Jupyter provides various extensions like git integration, specialized widgets etc.\n", "\n", "Besides kernel and frontend, a Jupyter installation consists of the language agnostic backend part that manages kernels, notebooks and the communication with the frontend. This component is called the Jupyter server. Notebooks are stored in .ipynb files, encoded in a Json format on the server. The Json based format allows storing cells inputs, outputs and metadata in a structured way. Binary output data is base64encoded. The disadvantage is that the json makes diff and merge harder, compared to line based text formats. You can export notebooks into other formats such as Markdown, Scala (contains only code input cells), or HTML like this article." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter and Scala\n", "\n", "How does support for Jupyter look like in Scala? There's actually a number of different Scala kernels available. If you look closer though, many of them are somewhat limited in features, have scalability issues or have even been abandoned. Others are focused exclusively on Spark rather than Scala in general and other frameworks.\n", "\n", "One reason for that is that almost all existing kernels build on top of the default REPL. Due to its limitations, they customize and extend it to add their own features such as dependency management or framework support. Some kernels also use the Spark Shell which is basically a fork of the Scala REPL customized for Spark support. This all leads to fragmentation, difficulty of reuse and duplication of work, making it harder to create a kernel that is on par with other languages.\n", "\n", "For a more detailed discussion about some of the reasons check out this talk at JupyterCon 2017 by Alexandre Archambault:\n", "\n", "
\"Scala:
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The Almond Scala Kernel\n", "\n", "Fortunately, recent developments have changed the situation. We've already talked about Ammonite and the improvements it has over the default REPL. Couldn't we leverage some of Ammonite's features for a Scala kernel as well? And that's exactly what **[Almond](https://almond-sh.github.io/almond/stable)** (formerly called jupyter-scala) by Alexandre Archambault does. By building on top of Ammonite, Almond can directly benefit from many of its features.\n", "\n", "For instance, dynamic dependency resolution works exactly the same way as in Ammonite:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import $ivy.`org.typelevel::cats-core:2.0.0`\n", "import cats.syntax.semigroup._ // for |+|\n", "import cats.instances.int._ // for Monoid\n", "import cats.instances.option._ // for Monoid\n", "\n", "Option(1) |+| Option(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The same is true for syntax highlighting, pretty printing and autocompletion." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Seq.fill(5)(Seq.fill(3)(\"Foo\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Building on Ammonite also highlights a more general design principle of Almond. It tries to delegate as much functionality as possible to existing components instead of reinventing the wheel. Doing so allows it to stay more lightweight, easier to understand, and to better focus on its core functionality as a kernel. While Almond has used a forked version of Ammonite for some time, the changes have been upstreamed and it now includes stock Ammonite. This is unlike other kernels which have often heavily customized and extended the Scala REPL to fit their needs.\n", "\n", "Almond is not tied to a specific big-data framework like Spark. That doesn't mean we can't have framework integrations, quite on the contrary. But the idea is to do bridging and integration in more standardized way instead of having to customize the REPL or the kernel itself. Ideally, the integration is done as a module or a separate library that talks to the kernel via well defined APIs. For interfacing with a Spark cluster for instance, Almond relies on [ammonite-spark](https://github.com/alexarchambault/ammonite-spark) in combination with providing a Jupyter specific Spark module.\n", "\n", "Due to its modular design and well defined interfaces, Almond even makes it easy to create your [own custom kernel](https://almond-sh.github.io/almond/stable/docs/dev-custom-kernel). For more info about Almond's features, check out its [project website](https://almond-sh.github.io/almond/stable/docs/intro).\n", "\n", "Almond development (through its creator and main developer) is currently funded by the Scala Center but there's still a lot to be done, like adding more integrations or improving the code editor experience for Scala. If you'd like to contribute, PRs are very much welcome!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Combining the Advantages of REPLs and Worksheets\n", "\n", "Let's now get back to the question how Jupyter notebooks combine the advantages of REPLs & worksheets. In a sense, you can think of a notebook as a REPL of worksheets (cells).\n", "\n", "Each code cell roughly corresponds to a worksheet. You have an editor window to enter your expressions, and once you hit run, **all** expressions in a cell are evaluated in one go and the outputs are shown below.\n", "Since notebooks are files, you can also save them, share them and put them under version control like worksheets. So the behaviour inside a cell is basically worksheet like, except that by default, the output is not on the right hand side but below the cell. \n", "\n", "A Jupyter notebook can have as many cells as you like, though, and at the document level it behaves more like a REPL. You enter one or more expressions in a cell, run it, perhaps refine and run again a few times until you're happy. Then you create a new cell below the current one (which may depend on values from the cell above) and repeat the process.\n", "The way you can control which cell will be executed is actually even more flexible. You can, for instance\n", "* select any cell and (re-)run it\n", "* Run all cells, or all cells above/below the currently selected cell\n", "* Insert a new cell anywhere, or delete an existing one\n", "* copy and paste cells\n", "* easily rearrange cells as you like\n", "* merge or split cells\n", "\n", "That's a very powerful toolbox for experimentation. Because you can execute and rearrange cells arbitrarily, sometimes you end up with cells containing expressions which depend on values from cells below. \n", "This can be very confusing so you should make sure that your code runs fine when executing your notebook in linear order, especially if you want to share it. There's a talk called [I Don't Like Notebooks](https://youtu.be/7jiPeIFXb6U) by Joel Grus about those traps and about Jupyter notebooks from a Software Engineering perspective.\n", "\n", "\"Jupyter\n", "\n", "Since cells in one notebook share the same kernel and its interpreter variable state, they can depend on values computed by other cells executed earlier.\n", "So you could have a cell on top of your notebook that loads a large dataset or runs a complex computation and the results will be cached and available to all cells executed later, as long as the kernel isn't restarted. In essence, notebooks defuse the main disadvantage of worksheets by combining its execution model with the one of the REPL.\n", "\n", "While outputs are shown below a cell by default, interleaving of input and output is between cells, not between single expressions as in The REPL. That means you can always see the code of a cell as a whole. You can also easily clear the output of a cell or of all cells to see all your inputs more clearly. Last but not least can you also export your notebook as a Scala file containing all your code input cells." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rich, Interactive Computing in your Browser\n", "\n", "Another very important reason why Jupyter notebooks are so successful is their web based frontend and how we can interact with it. As we've already seen, we can add documentation cells with Markdown formatting including images or other HTML elements. But what makes notebooks **really** powerful is that the Jupyter API allows us to send rich outputs from the kernel to the frontend.\n", "\n", "We can generate generate dynamic web content on the fly in our code, accessing any data source available and send it to the frontend. That way, we can display basically anything the browser supports such as *tables*, *images*, *charts* etc. straight from our code. We can even send JavaScript from the kernel that will be executed in our frontend. And that JavaScript can communicate with the kernel through the Jupyter API i.e. for interactive input widgets.\n", "\n", "This powerful idea is best illustrated with a few examples:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import almond.interpreter.api.DisplayData\n", "\n", "display(\n", " DisplayData(\n", " Map(\n", " \"text/html\" -> \"Some HTML\")))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The kernel API provides a `display` method that takes expects our content, together with its mime-type.\n", "We can also send *multiple representations* of the data we want to display (keyed by mime-type), and the frontend will pick and show the most specific one it supports:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "display(\n", " DisplayData(\n", " Map(\n", " \"text/plain\" -> \"Some text\",\n", " \"text/html\" -> \"Some HTML\")))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Almond provides and automatically imports some convenience helper methods for common mime-types in `almond.api.helpers.Display`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Html(\"Some HTML\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also register a `Displayer` for any type via [JVM Repr](https://github.com/jupyter/jvm-repr), a project for \"standardizing object representation and inspection across JVM kernels (Scala, Clojure, Groovy, ...)\".\n", "\n", "Let's see how a list of `people` is displayed by default:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "case class Person(name: String, age: Int)\n", "case class People(people: Seq[Person])\n", "\n", "val people = People(\n", " Seq(\n", " Person(\"alice\", 29),\n", " Person(\"bob\", 23),\n", " Person(\"charlie\", 34)\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's add a displayer for `People` and see how it is displayed:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import $ivy.`com.lihaoyi::scalatags:0.7.0`\n", "\n", "import jupyter.Displayer, jupyter.Displayers\n", "import scala.collection.JavaConverters._\n", "\n", "// Note that as of now this approach doesn't seem to work with parameterized types like Seq[Person]\n", "// which is probably due to type erasure.\n", "Displayers.register(classOf[People], (people: People) => {\n", " import scalatags.Text.all._\n", " Map(\n", " \"text/html\" -> {\n", " table(cls:=\"table\")(\n", " tr(th(\"Name\"), th(\"Age\")),\n", " for (Person(name, age) <- people.people) yield tr(\n", " td(name),\n", " td(age)\n", " )\n", " ).render\n", " }\n", " ).asJava\n", "})\n", "\n", "people" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pretty neat huh?\n", "\n", "The idea is that library authors can provide `Displayers` for types i.e. for a Spark `DataFrame` and once you have it imported it you will get a nicely formatted representation of your data.\n", "\n", "There are also helpers for images." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Image\n", " .from(\"https://almond.sh/logos/impure-logos-almond-3b.png\")\n", " .withWidth(150)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see a more advanced example. We can easily plot nice, interactive charts directly in our notebook using [Plotly](plot.ly) and the [plotly-scala](https://github.com/alexarchambault/plotly-scala) bindings." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import $ivy.`org.plotly-scala::plotly-almond:0.7.1`\n", "import plotly._, plotly.element._, plotly.layout._, plotly.Almond._\n", "{{ \n", " val trace1 = Scatter(\n", " Seq(1, 2, 3, 4),\n", " Seq(0, 2, 3, 5),\n", " fill = Fill.ToZeroY\n", " )\n", "\n", " val trace2 = Scatter(\n", " Seq(1, 2, 3, 4),\n", " Seq(3, 5, 1, 7),\n", " fill = Fill.ToNextY\n", " )\n", "\n", " val data = Seq(trace1, trace2)\n", "\n", " plot(data)\n", "}}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we use the ability to send JavaScript to generate inject the plotly widget into our frontend. Newer frontends like JupyterLab and nteract are more restrictive about JavaScript execution for security reasons. That's why plotly-scala also sends a json representation of our plot which is then rendered by nteract or the [JupyterLab Plotly extension](https://github.com/jupyterlab/jupyter-renderers/tree/master/packages/plotly-extension).\n", "\n", "### Communicating results\n", "\n", "The ability to generate and display rich (and possibly interactive) outputs is an invaluable tool for interactive data exploration and analysis, machine learning, and science experiments. That's why interactive notebooks have recently been named the third most important tool for data scientists.\n", "Being able to show your code side-by-side with documentation, rich outputs and visualizations can be a very effective way to communicate results.\n", "\n", "### Teaching and Learning\n", "\n", "Notebooks are also an interesting tool for teaching and learning. They can help you to create executable tutorials, docs and examples.\n", "For instance, I've recently converted the [Scala Tour](https://docs.scala-lang.org/tour/tour-of-scala.html) into a set of Jupyter notebooks you can run on [Binder](https://mybinder.org/v2/gh/almond-sh/examples/master?urlpath=lab/tree/scala-tour%2Fbasics.ipynb).\n", "\n", "
\n", "\n", "### Visualize your data structures\n", "Or how about experimenting with a nice inline visualization of your data structures using the amazing [reftree](https://stanch.github.io/reftree/) library?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import $ivy.`io.github.stanch::reftree:1.4.0`\n", "\n", "{{\n", " import reftree.render._, reftree.diagram._\n", " import reftree.contrib.SimplifiedInstances.string\n", " val renderer = Renderer(renderingOptions = RenderingOptions(density = 75))\n", " \n", " case class Person(name: String, age: Int)\n", " val people = List(\n", " Person(\"Alice\", 29),\n", " Person(\"Bob\", 23),\n", " Person(\"Charlie\", 34)\n", " )\n", "\n", " renderer.render(\"example\", Diagram.sourceCodeCaption(people))\n", "}}\n", "Image.fromFile(\"example.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusion\n", "\n", "I hope that I could convince you that Jupyter notebooks are a powerful and incredibly flexible tool for interactive computing. \n", "As we've seen, they combine many strengths of the REPL and worksheets, while also adding unique new features.\n", "Their web-based interface, interleaving code with documentation, and the ability to send rich outputs from your code to the frontend give you a wealth of possibilies for things like prototyping, data visualization, communication of results, and teaching.\n", "\n", "The [Almond kernel](https://almond-sh.github.io/almond/stable) makes that power available for Scala, including all the niceties of Ammonite. Even though it still needs some more integrations and documentation, it's already quite usable and fun to work with.\n", "\n", "To see more examples of what's possible with Jupyter and Almond, check out the [examples repo](https://github.com/almond-sh/examples). It consists of a growing collection of Jupyter notebooks, each containing executable Scala code. You can run all these notebooks in your browser without any local setup, [using Binder](https://mybinder.org/v2/gh/almond-sh/examples/master?urlpath=lab).\n", "\n", "If you have any questions or feedback, don't hesitate to leave a comment, or ping me on Twitter [@soebrunk](https://twitter.com/soebrunk)." ] } ], "metadata": { "kernelspec": { "display_name": "Scala (2.12)", "language": "scala", "name": "scala212" }, "language_info": { "codemirror_mode": "text/x-scala", "file_extension": ".scala", "mimetype": "text/x-scala", "name": "scala", "nbconvert_exporter": "script", "version": "2.12.10" } }, "nbformat": 4, "nbformat_minor": 4 }