<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Johan Hidding on Medium]]></title>
        <description><![CDATA[Stories by Johan Hidding on Medium]]></description>
        <link>https://medium.com/@jhidding?source=rss-ee75caffdf66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*orS2D81amxeghWBa.jpeg</url>
            <title>Stories by Johan Hidding on Medium</title>
            <link>https://medium.com/@jhidding?source=rss-ee75caffdf66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:47:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jhidding/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Diversity in Software: four ways to think different]]></title>
            <link>https://medium.com/escience-center/diversity-in-software-four-ways-to-think-different-ee4eaf72af79?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee4eaf72af79</guid>
            <category><![CDATA[programming-paradigms]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 09:02:30 GMT</pubDate>
            <atom:updated>2023-02-02T09:02:30.346Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UEj6pL6ULRRtj9Tb" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Diversity is a hot topic. Let’s talk about diversity in Software. Hackers need to wake up and face the truth: a lot of programming paradigms are underrepresented in the mainstream media. All the talk is about Python, Rust, Kotlin, and Julia. All of them are imperative languages. This just leaves no room for us wayward farers to express ourselves and be ourselves!</p><p>People who know me now think the rest of this piece is going to cover the other side of the isle: functional programming, but they’re wrong. Just two approaches to programming are not enough. The funny thing is, you will have heard of most of the languages that I will talk about. I’ll just teach you to treat them with a little more respect.</p><h4>Make</h4><p>Make is a dependency-based programming language. You state a set of requirements, then other requirements for those, and so on. Then Make figures out a way to meet this cascade of requirements until your original goal is reached. This is a radical departure from imperative-style programming, where you have to be more explicit in what order you would like things to happen.</p><h4>Awk</h4><p>Awk is a data streaming language. Given that you have some input file, Awk triggers actions on some regular expressions that you provide. This is ideal for processing text files. Because Regexes play a central role in the execution model of Awk, programs tend to suffer in readability. What you need to realize is how awesome the concept of Awk is. The rule-based control flow makes your program context-aware.</p><h4>SQL</h4><p>In a landscape where the increasingly popular databases are graph-based or NoSQL, we need to champion our old hero: SQL. There’s nothing quite like juggling tables and inner joining them in holy matrimony. There’s a good reason why most databases work with tables and relations: for most cases, it is very efficient. The little extra effort of designing a table layout and indexing your data at strategic points is always well spent, as you gain insight into your problem.</p><h4>Excel</h4><p>Say what!?! Excel is at its core a functional reactive programming language. Your data is a signal. Every time the signal changes all the depending cells are notified and updated live. Frameworks that generalize on this concept are known as functional reactive. I know Excel has its share of problems: cells that are not included in the computation, bad type heuristics, poor scaling… However, at its core Excel is a beautiful diamond that needs to be celebrated.</p><p>Ok, those were some very famous languages. What you need to understand is how they are different. Their diversity can teach you not to take the mainstream general-purpose programming sludge for granted.</p><p>In fact, the particular way that these languages or systems are different may teach you how to think about some problems on a higher level. The primitives of SQL are available in Python (and many other languages): for small things, you can use iterator comprehensions or the itertools library.</p><p>If your problem has a complex set of interlocking dependent tasks (like you’d have in Make), consider writing the dependencies down in a data structure and evaluate them using Asyncio or Dask. This helps separate the core logic from implementation details, giving you cleaner, i.e. more readable and better maintainable code.</p><p>The same goes for Awky problems: if you need to filter through a lot of text, write down some rules for a little state machine. Your life will improve!</p><p>As for Excel: (functional) reactive programming is a topic I can’t possibly do justice to here. For those interested: <a href="https://blog.oakbits.com/introduction-to-rxpy.html">Introduction to RxPy</a>, or more generally <a href="https://www.manning.com/books/functional-reactive-programming">Introduction to Functional Reactive Programming</a>.</p><p>What these languages have in common, is that they have a different <em>control flow</em> from what you’re used to. Knowing how to work with these tools can be an invaluable addition to your skill set. Did I miss out on any? Please comment below!</p><p>If you’re interested in programming language history, check out this video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmRwHZTNGdoY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmRwHZTNGdoY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmRwHZTNGdoY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a61c4e8af10662f9360438d6792c50/href">https://medium.com/media/54a61c4e8af10662f9360438d6792c50/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee4eaf72af79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/diversity-in-software-four-ways-to-think-different-ee4eaf72af79">Diversity in Software: four ways to think different</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unweaving legacy code using Entangled]]></title>
            <link>https://medium.com/escience-center/unweaving-legacy-code-using-entangled-2e6380a88b2f?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6380a88b2f</guid>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[literateprogramming]]></category>
            <category><![CDATA[open-science]]></category>
            <category><![CDATA[programming-paradigms]]></category>
            <category><![CDATA[reproducibility]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 14:32:36 GMT</pubDate>
            <atom:updated>2022-11-10T14:32:36.742Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>For a Research Software Engineer, dealing with legacy code is seen as a chore: dirty work, but a necessary evil. But the truth is, every time I read someone else’s code, I learn something. Using Entangled to work out how some obscure code works also makes it kind of fun!</p><figure><img alt="Old punchcard as epitome of legacy code" src="https://cdn-images-1.medium.com/max/1024/1*ilw6P_BRplg-NVlLgG_zRQ.jpeg" /><figcaption>Punchcard (credit: <a href="https://www.flickr.com/people/93001633@N00">Pete Birkinshaw</a> from Manchester, UK)</figcaption></figure><p>On a typical day in the life of a Research Software Engineer (RSE), out on the prairies of academia, scavenging for source code, the RSE often encounters source codes for computer programs that have a lot to be desired in terms of readability, reusability, and, to summarize, in terms most modern standards. RSEs have coined a few derogatory terms for these code bases: <em>PhD-ware</em>, <em>labware,</em> or, heaven forbid, <em>professor-ware</em>. The proper academic name for these creatures is <em>legacy code.</em></p><p>How we handle these codes depends entirely on the situation. Suppose the correct functioning of the software is responsible for some important research output. We would like to reproduce the said output, or at the very least understand <em>exactly</em> how these results were obtained. In an ideal case, it should be enough to read the corresponding journal article and see that it matches what is done in the code. Then we can start changing the model or fiddling with newer data and derive our own conclusions.</p><p>When first faced with a new body of source code, the task of disentangling exactly how it works can be quite daunting. In many legacy codes, readability was not a primary concern. In science land it is “<em>publish or perish”</em>, never mind documenting your code. <strong>How can we figure out the inner workings of a code in a systematic way, such that the next pair of eyes will have an easier time?</strong> This is where <a href="https://entangled.github.io/">Entangled</a> comes in.</p><p>Entangled is an engine for doing <a href="https://blog.esciencecenter.nl/literate-programming-in-science-1669094541a7">literate programming</a> in Markdown. This means you can write entire computer programs from code blocks embedded in a reader-friendly Markdown document. Code blocks can <em>quote</em> other code blocks by including &lt;&lt;reference&gt;&gt; tags. Entangled replaces these tags with their content in the final output source code. This way, we take a source code apart while the functioning of the compiled program is completely preserved.</p><p>So, how do we attack the problem of dissecting our unknown code base? We start with a Markdown file containing, in a code block, the code that we’re interested in. If we find interesting bits, cut out the relevant code, put it in a separate block, and replace it in the original code with a reference. The Markdown lets us put parts of the code in different sections, and add documentation, derivations, tables, references, or even our own thoughts. Repeat until satisfied.</p><p>Depending on the size of the project you may want to disentangle just a few essential files in this manner, or perhaps you prefer to deconstruct the entire code. It doesn’t matter. The resulting Markdown files can be converted for online reading using any of your favourite tools: Pandoc, MkDocs, Jekyll, you name it.</p><h4>Examples</h4><p>This all doesn’t mean much without a decent example, so let&#39;s see a couple of them.</p><p>The first example we’ll look at is one that I picked from Rosetta Code. It’s an implementation of the game <a href="https://rosettacode.org/wiki/Snake#UNIX_Shell">Snake in Bash</a>. Since Bash can be quite a dense language to read, we may learn a lot by destructuring even this tiny program.</p><figure><img alt="Screenshot of webbrowser" src="https://cdn-images-1.medium.com/max/1024/1*jxEcYwxE1UA_d2o1PbRylw.png" /><figcaption>Legacy code, looking readable thanks to Entangled</figcaption></figure><p>As far as Bash scripts go, this is reasonably clean code, so not your worst nightmare. I encourage you to take a look at the full result at <a href="https://jhidding.github.io/shell-snake">jhidding.github.io/shell-snake</a>. As you may see, I have split the program into three parts: setup, main loop, and post-mortem. If I were more interested, I could further pull apart some expressions, building a deeper hierarchy. If I’m unhappy with some part, I can swap out some code in a well-documented manner.</p><p>The second example is a bit bigger. Also, this time I’ve translated the source code from C++ to Rust. There is a 100-sloc C++ code for ray tracing a set of spheres by Kevin Beason, called <a href="https://www.kevinbeason.com/smallpt/">SmallPT</a> (it is quite famous in some circles). While the original is focused on getting as much as possible into a hundred lines of code, I wanted a bit more understanding. A ray tracer computes an image by doing a physical simulation of millions of photons in a given scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wtAt6IzGk2lxdeQw1lf9g.png" /><figcaption>A ray-traced rendering of a few spheres.</figcaption></figure><p>The full demo can be found here: <a href="https://jhidding.github.io/literatept/">jhidding.github.io/literatept</a>. I made some algorithmic changes to the original that are well documented. See for instance the <a href="https://jhidding.github.io/literatept/#path-tracing">section on path tracing</a>. In another instance, I tried to understand the underlying physics of <a href="https://jhidding.github.io/literatept/#partial-reflection">reflecting rays in the transparent sphere</a>. There I was able to underpin the code with equations and references.</p><blockquote>Does this sound interesting to you? Then you may like to get Entangled at <a href="https://entangled.github.io/">https://entangled.github.io/</a>.</blockquote><blockquote>Also read my other blog posts about <a href="https://blog.esciencecenter.nl/literate-programming-in-science-1669094541a7">Literate Programming in Science</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6380a88b2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/unweaving-legacy-code-using-entangled-2e6380a88b2f">Unweaving legacy code using Entangled</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Literate Programming in Science]]></title>
            <link>https://medium.com/escience-center/literate-programming-in-science-ed94dcc8f758?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed94dcc8f758</guid>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[jupyter]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[open-science]]></category>
            <category><![CDATA[literateprogramming]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Wed, 07 Jul 2021 14:40:37 GMT</pubDate>
            <atom:updated>2021-07-07T14:40:37.810Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ke-o36ZPmah-PK4" /><figcaption>Photo by <a href="https://unsplash.com/@prateekkatyal?utm_source=medium&amp;utm_medium=referral">Prateek Katyal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>2. The How</h4><p><em>This is part 2 in a series on Literate Programming in Science. If you haven’t yet, </em><a href="https://blog.esciencecenter.nl/literate-programming-in-science-1669094541a7"><em>please read part 1 “The Why”</em></a><em>.</em></p><blockquote><strong><em>Literate programming</em></strong><em> /ˈlɪtəɹət ˈpɹəʊɡɹæmɪŋ/ (computing) Literate programming is a programming paradigm introduced by Donald Knuth in which a program is given as an explanation of the program logic in a natural language, such as English, interspersed with snippets of macros and traditional source code, from which a compilable source code can be generated. </em><a href="https://en.wikipedia.org/wiki/Literate_programming"><em>Wikipedia</em></a></blockquote><p>If you’re reading this, then I hope I’ve convinced you (or maybe you didn’t need convincing) of the necessity of Literate Programming in Science. The next question should be: where do I start? I will discuss three methods of Literate Programming that you can use today, their upsides and downsides, what-have-you-not.</p><p>First, I should explain some nomenclature surrounding the concept of Literate Programming. The idea is that you write documentation first, interspersed with code blocks that actually implement the described ideas. These code blocks can be named and referenced from other code blocks using a system of references called <em>Noweb</em>. A special program is needed to extract all the code blocks from the markup and put them in the right order so that a well formed program code emerges on the other end: a process known as <em>tangling</em>.</p><p>A literate form of “Hello, World” in C++ would look something like this:</p><h3>Hello World</h3><p>This example is written in a style of <em>literate programming</em> (Knuth 1984). The combined code-blocks in this example compose a compilable source code for “Hello World”. For didactic reasons we don’t always give the listing of an entire source file in one go. In stead, we use a system of references known as <em>noweb</em> (Ramsey 1994).</p><p>Inside source fragments you may encounter a line with &lt;&lt;...&gt;&gt; marks like,</p><pre><em>«hello_world.cc»=</em><br>#include &lt;cstdlib&gt;<br>#include &lt;iostream&gt;</pre><pre>&lt;&lt;example-main-function&gt;&gt;<br>@</pre><p>which is then elsewhere specified. Order doesn’t matter,</p><pre><em>«print-message»=</em><br>std::cout &lt;&lt; &quot;Hello, World!&quot; &lt;&lt; std::endl;<br>@</pre><p>So we can reference the &lt;&lt;print-message&gt;&gt; code block later on.</p><pre><em>«example-main-function»=<br></em>int main(int argc, char **argv) {<br>  &lt;&lt;print-message&gt;&gt;<br>}<br>@</pre><p>A definition can be appended with more code as follows (in this case, order does matter!):</p><pre><em>«print-message»+</em>=<br>return EXIT_SUCCESS;<br>@</pre><p>These blocks of code can be <em>tangled</em> into source files, in this case a single hello_world.cc would emerge.</p><p>This “Hello World” shows just how you can combine the contents of code blocks to create a fully functional “Hello World” in C++. More examples of this type of literate programs can be found on the <a href="https://entangled.github.io/examples">Entangled website</a>.</p><p>The Noweb method of literate programming is not the only way to mix documentation with code. Not all methods described here have all the features that you would expect from Knuth’s original invention. In fact the most popular incarnation of Literate Programming arguably is that of notebooks. We may judge each method by their ease of use, and if they fit the bill of generating publishable and reproducible scholarly products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E5I_DM8KaxUxkDNf" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Notebooks (in particular Jupyter)</h3><p>The most common form of Literate Programming found in todays jungle of digitized science is the <em>notebook</em>. Personally my first encounter with notebooks was with the use of Mathematica, which featured notebooks as early as 1988. Many commercial packages for data analytics and modelling featured notebook interfaces long before the rise of <a href="https://jupyter.org/">Jupyter notebooks</a> in 2014. What makes Jupyter special is that it is an open source solution for many different languages (as long as someone took the effort of writing a Jupyter kernel for it).</p><h4>Pros:</h4><ul><li><strong>Dynamic evaluation</strong></li><li><strong>Easy interface</strong></li><li><strong>Easy sharing</strong> with MyBinder or related tools</li><li><strong>Language agnostic (in theory)</strong></li></ul><h4>Cons:</h4><ul><li><strong>No support for Noweb references or tangling</strong>: the code is evaluated in any possible order, depending on user interaction.</li><li><strong>Only really meant for end-of-line products</strong>: it is not expected that you write a Python library in a Jupyter notebook that someone else can import. It can be done in the case of Python (<a href="https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Importing%20Notebooks.html">see Jupyter docs</a>), but just reading the documentation should instill a deep feeling that you really shouldn’t.</li><li><strong>Only works for evaluated languages</strong>: because notebook interfaces are designed to be interactive, they are fundamentally limited to languages that provide a Read-Evaluate-Print loop (or REPL for short). Examples of languages that don’t have this are Java, Rust, Go (I would like to include C++ here, but there is Cling, the complexity of which is an argument against itself). In the case of Haskell we do have a REPL, but it doesn’t expose the full language.</li><li><strong>Crappy text editor</strong>: With Jupyter you’re stuck with the default inline text editor of Jupyter. If you use VSCode, you can edit notebooks directly from there, but the interface is still quite slow and buggy.</li><li><strong>Hard to debug</strong>: The latest version of Jupyter has a debugger for Python, I’m not sure if this debugger translates well to other languages.</li><li><strong>No stable API</strong>: This is not a principal argument, but a practical one. The Jupyter API changes often. As a consequence, the only kernel that can be expected to always work is the Python one. I’ve experienced frequent breaks when using Jupyter, even in the relatively common case of GNU R. For most other languages, sadly, chances are that you will have to experiment with downgrading Jupyter.</li><li><strong>Stored in JSON</strong>: the contents of the notebook are stored in JSON, even opening a notebook changes its contents. This is especially annoying when working with <strong>git</strong>.</li></ul><p>Some of these downsides may lessen or disappear entirely as Jupyter improves. The first three however are rather fundamental to the method. That is no critique. I love working with Jupyter and use it every day. It just isn’t for everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VXW1HQh6uiOo2ftU" /><figcaption>Photo by <a href="https://unsplash.com/@mrafonso1976?utm_source=medium&amp;utm_medium=referral">Margarida Afonso</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>RMarkdown and Knitr (with RStudio)</h3><p>RMarkdown was designed as the Literate Programming solution for R, with a focus on reproducibility. As the name suggests, it is a dialect of the markdown language.</p><p>Contrary to Jupyter, RMarkdown is more focused on creating high-quality documents than on interactivity, making it a perfect choice for writing vignettes, reports and even academic papers.</p><p>RMarkdown is particularly easy to learn and to use from RStudio. Nowadays it supports several languages apart from R, such as Python or SQL.</p><h4>Pros:</h4><ul><li><strong>Easy to install:</strong> (comes by default with RStudio)</li><li><strong>Dynamic evaluation:</strong> only if desired.</li><li><strong>Easy interface</strong>: RMarkdown is very accessible to new users through the RStudio interface, but it is possible to use it outside RStudio.</li><li><strong>Easy sharing:</strong> with RPubs, MyBinder or related tools.</li><li><strong>Plain text:</strong> Well defined plain-text format, in this case Markdown.</li><li><strong>Fixed order of evaluation:</strong> The code is evaluated sequentially by default. Other than with Jupyter, where the order of execution depends on user interaction.</li><li><strong>Language agnostic (in theory): </strong>many languages are supported through the <em>Knitr engine</em>.</li><li>Fancy functionalities are constantly added by the R community, such as caching for long calculations, support for different languages, cross-referencing, templates, etc.</li></ul><h4>Cons:</h4><ul><li><strong>No support for Noweb references or tangling</strong>: the code is evaluated in the order that you enter it.</li><li><strong>End-of-line:</strong> It is not expected that you write an R package in a RMarkdown file that someone else can import. Usually, the RMarkdown files are an addition to a package.</li><li><strong>Hard to debug</strong></li><li><strong>Language centric:</strong> The integration with languages other than R happens through R packages. Most of these packages are quite well designed and just work out-of-the-box, but for some of them you may need to invest learning how they work.</li></ul><p>Just as Jupyter, RMarkdown is a great tool to get started with Literate Programming. It stops just shy of being able to create fully compilable files from the literate sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1arvThu4tV8Y4Zuy" /><figcaption>Photo by <a href="https://unsplash.com/@brisch27?utm_source=medium&amp;utm_medium=referral">Brigitta Schneiter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Emacs org-mode</h3><p>While <a href="https://orgmode.org/">Org-mode</a> is not terribly well known, it offers one of the most complete solutions for Literate Programming that you can find. Me myself, I’m a born Vim user. Every now and then I take these editor excursions: VSCode lasted a week before I went back screaming for Vim. For this single feature of Org-mode I nearly switched to Emacs. I tried <a href="https://spacemacs.org/">SpaceMacs</a> for about <em>half a year</em> until reverting back to Vim. <em>That is how good Org-mode is (26x all of VSCode if you can count). </em>Many adepts describe it as a life changer.</p><p>In essence Org-mode is an editor mode that helps you edit nestings of unordered lists, it’s main use being for brainstorming and keeping todo lists. From these humble beginings sprouted a markup language that, entirely in the Emacs tradition, includes everything and the kitchen sink (did I mention the spreadsheet?). Today Org-mode could be considered a variant on other markup languages like Markdown and reStructured Text. What makes Org-mode special is the way you can edit and interact with it inside Emacs.</p><p>One of the many features of Org-mode is that it supports code-blocks <em>with noweb references</em>. These code-blocks can be evaluated inline (using one of many plugins available for Emacs) or tangled to runnable/compilable source files.</p><h4>Pros:</h4><ul><li>Supports noweb and tangling.</li><li>Well defined plain-text format.</li><li>Export to nearly anything.</li><li>Dynamic evaluation of code blocks.</li><li>Completely language agnostic.</li><li>Plain text markup.</li></ul><h4>Cons:</h4><ul><li>Only works as intended in <strong>Emacs.</strong></li><li>Collaborators would have to use <strong>Emacs.</strong></li><li>Debugging should be done from <strong>Emacs.</strong></li></ul><p>In its own way Emacs is awesome. If this fits the bill for you, by all means shape your life around it, join the church. I do believe however, that this is not something you can force onto someone else.</p><p>What all the previous methods share is that they drive you into using a chosen set of tools, each with its own particular down sides. What I am aiming for is a method of Literate Programming that is feature complete and <em>minimally intrusive</em>. Feature completeness is always a matter of personal taste, nevertheless I will give it a shot:</p><ul><li>Deconstruct code using Noweb syntax, or something very close to it.</li><li>Be completely language agnostic.</li><li>Export to nearly everything.</li><li>Use a plain-text markup format.</li><li>Play nicely with existing methods for publishing on the web.</li></ul><p>One thing I didn’t include in there is the feature of dynamic evaluation. Such a thing could be achieved in a generic way by implementing editor plug-ins on top of the <a href="https://microsoft.github.io/language-server-protocol/">Language Server Protocol</a> (using a code action of some kind). Implementing an Org-mode kind of interaction in this way would be a very interesting project onto itself, but not today.</p><p>Instead, I introduce a new feature that none of the other methods have: the ability to work on tangled source code while keeping the original markup synchronized. This feature greatly improves the maintainability of the literate program while also opening up all the normal tools you’re used to work with: debuggers, linters, transmogrifiers, you name it. Let’s call this feature: <strong>live untangle mode</strong>.</p><h3>The Entangled Project</h3><p>I hope by now I have convinced you that A. Literate Programming is awesome and B. the current set of available tools are not sufficient. This is why I started <a href="https://entangled.github.io/">the Entangled project</a>. The goals of the Entangled Project are three-fold:</p><ul><li>Develop tools for Literate Programming</li><li>Arrive at a set of best practices</li><li>Communicate, teach and promote</li></ul><p>The push for these methods and best practices focusses on a system using <em>Markdown</em> as the primary markup language. I believe Markdown offers the ideal combination of readability and flexibility to suit most needs, a stance that I previously defended in a blog post: <a href="https://blog.esciencecenter.nl/why-all-youll-ever-need-is-markdown-dc604f0ab309">Why all you’ll ever need is Markdown</a>. This does not mean that the choice for Markdown is final; all of what we do carries over without problems to other formats.</p><h4>Tools</h4><p>The primary tool we have developed is Entangled. This is a daemon that runs while you edit the markup files or the tangled sources. Entangled keeps the two in sync so that you only ever have one version of the code.</p><p>Next to this core tool we have several experimental filters for <a href="https://pandoc.org/">Pandoc, the universal document converter.</a> These filters can do several things:</p><ul><li>Annotate generated output with headings for the named code fragments.</li><li>Evaluate code fragments by passing them through Jupyter.</li><li>Inject Javascript code fragments into the HTML output for interactive elements (e.g. PlotLy).</li><li>Generate Bootstrap UI elements, for example: foldable code blocks.</li></ul><p>The approach we take to Literate Programming has been battle tested using three different document converters: Pandoc, MkDocs and Docsify. Each generator works with a slightly different dialect of Markdown.</p><h4>Future plans</h4><p>Entangled is ready to use, but it is not too user friendly yet. For one, we expect you to setup your own pipeline for building the document for public release. Most often this would be some static HTML generator using Pandoc or MkDocs. Alternatively you can use Docsify to serve a website directly from the Markdown sources.</p><ul><li><strong>Getting started:</strong> The problem for entry level users is that it may not be trivial to set these up. The current template for working with Pandoc requires Pandoc (duh), GNU Make, browser-sync, some form of inotify-wait, and of course, Entangled. We’d like to make it much easier to start working on your own projects, so we’d like to bring this set of requirements back to just Entangled.</li><li><strong>Templates: </strong>We should provide easy to use starting templates for a set of popular document generators. The one currently still unmentioned being Sphinx. These templates should be initialized using an entangled init sub-command.</li><li><strong>Single file mode</strong>: The default operation of Entangled should be a single file mode (most probably README.md), and work out of the box with no configuration. Imagine a Github repository with just a README (and a LICENSE and a CITATION.cffand a .editorconfig and a … oh you get the point!) and a Github Action tacked on to generate the Github.io pages.</li><li><strong>Flexible code presentation:</strong> in the publicized output code cells are currently static. At the very least Noweb references should be clickable. Other features could include: links to the tangled output, be able to view the code in expanded form.</li></ul><p>Help is appreciated! Entangled is primarily developed in Haskell, though no skill in Haskell is required for example to create templates for working with Entangled. Pandoc filters can be developed in Python. In particular the filter for interacting with Jupyter could use some fresh ideas.</p><p><em>About the author: I’m (among other things) the developer of </em><a href="https://entangled.github.io/"><em>Entangled, a Literate Programming framework and toolset</em></a><em>. The main goal of this blog-post is to convince you that existing tools for Literate Programming are not yet ready to serve the needs of the broader scientific community.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed94dcc8f758" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/literate-programming-in-science-ed94dcc8f758">Literate Programming in Science</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Literate Programming in Science]]></title>
            <link>https://medium.com/escience-center/literate-programming-in-science-1669094541a7?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/1669094541a7</guid>
            <category><![CDATA[open-science]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[literateprogramming]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 12:54:33 GMT</pubDate>
            <atom:updated>2021-07-07T14:39:41.155Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JEhytH2Iryk_8pyE" /><figcaption>Photo by <a href="https://unsplash.com/@paulmelki?utm_source=medium&amp;utm_medium=referral">Paul Melki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>1. The Why</h4><blockquote><strong><em>Literate programming</em></strong><em> /ˈlɪtəɹət ˈpɹəʊɡɹæmɪŋ/ (computing) Literate programming is a programming paradigm introduced by Donald Knuth in which a program is given as an explanation of the program logic in a natural language, such as English, interspersed with snippets of macros and traditional source code, from which a compilable source code can be generated. </em><a href="https://en.wikipedia.org/wiki/Literate_programming"><em>Wikipedia</em></a></blockquote><p>Ever since the introduction of computers into the realm of natural sciences, software has been slowly replacing pure math as the main driver for advances in methodology. While it is considered to be absurd to write a paper in physics for instance without any equations, the same cannot be said for writing papers without code, weather it be ecological models, physics simulations or climatology. The accepted standard is that models are described in equations and some fancier algorithms possibly in pseudo code.</p><p>Literate Programming is an ancient art form. Maybe some older programmers would be insulted by calling something from the 80ies <em>ancient,</em> but what I really mean is that Literate Programming is a form of <em>teaching</em>. You simply explain, in words, what it is you’re doing. In that sense, Literate Programming is a method of communicating that should be at the heart and soul of every scientist that dallies with the computational aspects of the job. <strong>The arguments that I bring forth here touch upon the very foundations of what it means to do science.</strong></p><p>There are many arguments why or why you should not use Literate Programming when developing software. Many developers have learned how to think in terms of code. Good code should be self-explanatory, they say. And in a way, I agree: good code <strong>should </strong>be self-explanatory. Not every line of code should need explicit regurgitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eSbEboZgcfNWna7Y" /><figcaption>Bovine in the act of rechewing. Photo by <a href="https://unsplash.com/@askkell?utm_source=medium&amp;utm_medium=referral">Andy Kelly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>However, there are some major problems with this philosophy, if one might call it that. Did you ever wonder why it is that you learned reading before writing in literature, but not when it comes to computer programs? Sure, we learn the alphabet to start writing and reading, but to really write a coherent well structured story or essay? I’d say that happens roughly a decade after the ABC. With software however, it sometimes seems to take more effort to read a program than to write one. Why is this?</p><ol><li><strong>Hierarchy</strong>: Many code bases are hierarchical. A generic function might be defined only for very specific use in the code, or for many different uses. There have been some suggestions of writing ARCHITECTURE.md files to go along with a package.</li><li><strong>Abstractions</strong>: The code itself doesn’t encode the purpose behind it, only its function. This point bugs me to no end, maybe because I’m a trained physicist and not a mathematician? Many functions in a more complex code base deal with abstract quantities. It is considered a good practice to keep functions abstract so that they can be reused even if the circumstances are slightly different. It may turn out that our most generic defenition was not up to the task for our specefic case. As a result we may tweak the implementation or even the precise outcome of the function. What we are left with is called a <em>leaky abstraction</em>. To figure out why a function is implemented the way it is, we may need to know about its purpose elsewhere in the code.</li><li><strong>Intended use</strong>: in an ideal universe, intended use shouldn’t matter. Every unit of code is an island universe onto itself. But we all know that most code is far from ideal.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mm5KJs1KWJ6CdWvo" /><figcaption>Island Universes. Photo by <a href="https://unsplash.com/@gferla?utm_source=medium&amp;utm_medium=referral">Guillermo Ferla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Or maybe it is because we tend to underestimate the amount of effort that goes into writing a truly well written piece of software, and compared to natural language, we’re all still stuck in kindergarten?</p><p>To be clear, we are not contending the well accepted use of API documentation or tutorials. We should accept it as canon that those are very useful indeed. The difference is that those document the intended use of a library, following a strict client-server protocol. One person serves the software, another uses it as dictated by the prescription. While this may be the case in industrial software development, in science things are a bit different.</p><h3>Why scientific software is different</h3><p>Please forgive me for taking the easy way out, and arguing only for the use of Literate Programming in science: the argument is so much easier to make. There are several good reasons for this:</p><ol><li>In science, the division between software developer and user is not so clear cut. The developer and user ofter are the same person, leaving out an important quality control.</li><li>In science, code has meaning: a variable is not just container for a 64-bit IEEE 754 floating point value, this value describes something, has units, a physical interpretation. A variable can often be linked to a physical quantity that needs elaboration elsewhere in the text.</li><li>In science, it is often hard enough to reproduce results, even with the same data. People make mistakes, or with deadlines approaching, shove things under a very bumpy carpet.</li><li>In science, it is common enough to include equations in journal articles. These equations help other scientists convince that you worked really hard and that the subject is no trifle. At the same time, including bits of code is often a bit frowned upon. At the very best, to describe an algorithm you may include a piece of pseudo-code of which the semantics is some ill-defined form of Matlab. How do you even test pseudo code?</li><li>Scientists are not professional developers. We need more conduits to permeate best practices. Literate programming stimulates other people to actually read your code, while you’ll have an easier time reading other people’s code. This interaction should make better programmers of all of us.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QG3QEvXRdf1OYKcD" /><figcaption>If you make the carpet pretty enough, no one will notice! Photo by <a href="https://unsplash.com/@kadircelep?utm_source=medium&amp;utm_medium=referral">Kadir Celep</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Scientific works are supposed to be held to exacting standards. These standards are upheld by systems of peer-review and demands of precise reporting of methodology. These standards are often surprisingly lax when it concerns the use of software. This problem is for a large part addressed by the “Open Science” movement in general, stimulating the use of open source software in science. Still, even if code is open source, this does not mean that this code can be easily understood.</p><h3>21ˢᵗ Century science</h3><p>Ok, I’ve shown you the deepest pits of hell. Things aren’t all that bad, are they? There are some good initiatives in the Open Science movement. There is the Journal of Open Source Science that lets you publish your software. Also, there is an emerging practice of publishing your analysis pipeline in Jupyter notebooks on Zenodo. This is the absolute best you can hope for at the moment: kneel down on your bumpy carpet and praise your favourite deity!</p><p>What I’m saying is: this is not nearly good enough. All these solutions have seperate places for the scientific results and the code that produced them. As if the code is an ugly duckling that needs to be hidden from ignorant eyes. In a way these solutions are still holding to an old fashioned way of publishing on paper, with tight page limits. And I get it: science is tough. Tough enough without me bickering about transparency and reproducibility.</p><p>Then, what are we aiming for? We need to move scientific publishing into the current century: the century of Wikipedia and Github. Scientific information need not be bound to bundles of papers of decreasing length. We are building a trinity of data, code and knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMgM27wsW3H4RGXIQHyPfw.png" /></figure><p>Some would say code is data, which is true on a certain level, but what I mean by data is things that are measured in real life, or outcomes of previous computational experiments. Scientific data is stored in huge databases that are often publicly accessible. We have seen the movement of making data FAIR, Findable, Accessible, Interoperable and Reusable, and in general people have gotten the idea (I know, wishful thinking).</p><h3>FAIR Software?</h3><p>Then there is code: by now most funding agencies agree that scientific results should be produced with open source software. What no one agrees on, is what this should mean: sure, your code needs to be accessible somewhere, and have a license. Do we get penalized if we write bad code? Is the paper rejected? I’m digressing. Attempts are underway to define what the FAIR principles would mean in the case of software: see for instance <a href="https://fair-software.eu/">https://fair-software.eu/.</a></p><p>When it comes to scientific software, each package falls in roughly one of two categories: modelling and data analysis. While many scientists do a bit of both, these different categories require a different approach to development and especially documentation.</p><h4>Notebooks</h4><p>Analysis pipelines are often developed inside real-time environments like Matlab, RStudio and Jupyter (is this wishful thinking again?). These tools generally allow for a limited form of literate programming in the form of notebooks. Yes, notebooks are great for rapid development and data exploration, but they come with a few downsides: they don’t support the <em>noweb</em> syntax for decomposing codes into didactictally advantageous chunks, order of evaluation is generally not fixed, and they don’t work well with compiled languages. Jupyter Notebooks can be exported to Markdown, offering an easy transition from a “live” development stage to making the analysis ready for publication. RStudio offers a (almost) complete solution here with RMarkdown. In <a href="https://blog.esciencecenter.nl/entangled-1744448f4b9f">past</a> and future blog posts, I argue that <a href="https://entangled.github.io/">Entangled</a> offers a more generic method for Literate Programming, ideal for writing reports and papers.</p><h4>Modelling</h4><p>Where I think Literate Programming really shines, is in scientific modelling. When it comes to modelling, the code really is an extension of what you can do with mathematics. Writing a code helps you understand a system. The code is not just a translation of a model such that the computer can execute it. It is also a rigourous encoding of the model itself. We cannot mince words about what we’re doing: the code is absolute. This is exactly why we traditionally use equations to communicate the more exacting parts of our work.</p><p>I have worked out several examples that show how nicely equations and code mix when it comes to physical modelling:</p><ul><li>LiteratePT (<a href="https://jhidding.github.io/literatept/">https://jhidding.github.io/literatept/</a>) is my translation of Kevin Beason’s SmallPT 100 lines of C++ global illumination ray-tracer into Rust. It was a fun puzzle to figure out how this code really works!</li><li>Chaotic Pendulum (<a href="https://jhidding.github.io/chaotic-pendulum/">https://jhidding.github.io/chaotic-pendulum/</a>) is a demonstration of <a href="http://purescript.org/">PureScript</a> to model a chaotic double pendulum.</li><li>Adhesion model (<a href="https://jhidding.github.io/adhesion-code/">https://jhidding.github.io/adhesion-code/</a>) part of my thesis work, this C++ code uses CGAL (https://cgal.org/) to compute large scale structure of the Universe.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOoqQTMtnD9Ckcq3BSAiZA.png" /></figure><h3>Some concerns, some chances</h3><h4>Maintenance</h4><p>Talking to computer scientists, the major critique of Literate Programming in general, is that it hurts the maintainability of the code. While the code is excellently documented, it can be very hard to navigate the functionality of the code from a software architecture point of view. This is where <a href="http://entangled.github.io/">Entangled</a> comes in. Entangled makes it possible to edit the code both from the original Markdown as well as the generated source code. We <em>can</em> have the best of both worlds. Debugging and maintenance is done as before in the traditional way. Refactoring code sometimes actually becomes easier, since code can be moved around by changing a few directions in the Markdown files.</p><h4>Hybrid styles</h4><p>Every code contains boilerplate. It becomes a matter of taste how to deal with this in the context of Literate Programming. You don’t <em>need</em> to put everything in a literate style. It is perfectly possible to leave boilerplate code in normal source files.</p><h4>Layered programming</h4><p>Literate programming techniques also offer new paradigms for development. One such paradigm is <em>layered programming</em>. In this approach you can structure a code not just in modules but also in layers, each layer being a separate chapter or section in the literate code, while the modules organize the code in a traditional manner for the compiler. This gives an extra option for seperation of concerns, the code now having a two-dimensional organisation structure. One immediate example that comes to mind is the building of a command line tool with multiple sub-commands. Each command shares the same structure but adds different functionality. In a more scientific setting, this could be a model with increasing levels of complexity. Each layer may touch upon every part of the code, adding functionality to many different modules.</p><h3>Conclusion</h3><p>To conclude, Literate Programming can solve some real problems in the realm of Research Software Engineering and our means of publishing about software in science in general. Jupyter notebooks go a long way, but to my taste not far enough. The main reason for this is that scientists are not aware of the possibilities, while for computer scientists Literate Programming is something of a past station, of which the usefulness is debated.</p><p>It is high time that we identify areas where Literate Programming maybe has little added value, and others where it works great (there are plenty: did I mention writing tutorials?) Meanwhile, we need to improve our toolset (Entangled is not perfect yet), and develop a set of best practices when it comes to Literate Programming.</p><p><a href="https://blog.esciencecenter.nl/literate-programming-in-science-ed94dcc8f758"><em>Read on in Part 2: The How, on different existing methods for Literate Programming, where I discuss Jupyter Notebooks, RMarkdown and Emacs Org-mode along with my own ideas for Entangled.</em></a></p><p><em>About the author: I’m (among other things) the developer of </em><a href="https://entangled.github.io/"><em>Entangled, a Literate Programming framework and toolset</em></a><em>. The main goal of this blog-post is to convince you that Literate Programming is a good idea in the first place.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1669094541a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/literate-programming-in-science-1669094541a7">Literate Programming in Science</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lentil soup]]></title>
            <link>https://medium.com/@jhidding/lentil-soup-62a7ce8f3971?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/62a7ce8f3971</guid>
            <category><![CDATA[lentil-soup]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 18:11:24 GMT</pubDate>
            <atom:updated>2020-09-11T18:11:24.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CitnIl5Z0y8_eb9bt57-hg.jpeg" /></figure><p>These days I sometimes wonder, what is the best thing I can do for the world? How can I singlehandedly save humanity from near certain destruction? In the second wave of corona, and with the colder season approaching, nothing beats a good hearty lentil soup.</p><p>The basis is Japanese fish stock, Italian mashed tomatoes, Sambal (I recommend <a href="https://www.sambalbert.nl/">Bert’s</a>), lentils and water from the spring of eternal youth. Boil for 45 min. You won’t regret it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62a7ce8f3971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel programming in Python]]></title>
            <link>https://medium.com/escience-center/parallel-programming-in-python-7fd62c90217d?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fd62c90217d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[numba]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 16:04:34 GMT</pubDate>
            <atom:updated>2020-01-16T11:58:37.253Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p><strong>Part 1: Killing the GIL, Combining Dask and Numba for Parallel Number-Crunching in Python</strong></p><blockquote>This blog-post is co-authored by <a href="https://medium.com/u/24f09ca64482">Pablo Rodríguez-Sánchez</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z4ARblLhbeBbgubS" /><figcaption>Photo by <a href="https://unsplash.com/@randyfath?utm_source=medium&amp;utm_medium=referral">Randy Fath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever been in a hurry to complete a task? Most likely yes. There are two ways of minimizing your time spent on problems: one of them is to run faster… and the other one is to ask for help.</p><p>In many cases where the task is number crunching on a computer, programmers will move from a prototype in Python to a faster implementation in a different language (C++, Fortran or whatever). But what about Python itself? We will show that often it is not needed to move to C++ just for more performance. We solve our problem with Numba and Dask. Using these libraries in tandem make Python into a <strong>parallel number-crunching power-house</strong>.</p><h3>Parallel vs serial</h3><p>Conceptually, a computer is a machine that processes tasks. No more and no less. Most modern computers, including personal laptops, have many cores. Each core can process a task independently of the rest.</p><p>Most often, we use computers to perform collections of tasks. If those tasks are performed one after the other, we are talking about serial computation (see first figure).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*ooJOGfIS2703_zD_" /></figure><p>If at least some tasks can be performed simultaneously (as in the second figure), we are talking about parallel computation. By assigning one task to each core, we roughly multiply by 3 the speed of the whole process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/0*C1jtPbLg7Ntgvrgs" /></figure><h3>Pea soup and task parallelization</h3><p>Here’s a recipe for Dutch snert (it sounds even funnier when pronounced in English!), as it is given by one of the larger chains of supermarkets in the Netherlands (translated by Google’s translator app):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T31iV5cwLbnrvmvm" /></figure><p>If you look closely, it says at point 2 “Gently simmer in about 60 minutes”, followed by point 3, telling you to cut vegetables and point 4 &amp; 5, adding the vegetables to the soup. Any reasonable cook would cut the vegetables <em>while </em>the soup is gently simmering for about 60 minutes. Most traditional computer languages lack the power to express this idea succinctly, and will not optimise these tasks. We can do it, but we need to pull some tricks out of a hat. We will show how this can be done in Python using Dask.</p><p>We put the recipe in terms of Python functions, and make sure all our functions are <em>pure</em>: they only take arguments and give back a new result. Pure functions <em>do not mutate</em> a variable.</p><pre>from dask import delayed<br>from pint import UnitRegistry, Quantity<br>units = UnitRegistry()<br># Always use units, or else: (https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure)</pre><p>To add vegetables to the pan, we define the add_vegetable action:</p><pre>@delayed<br>def add_vegetable(pan: Container, ingredient) -&gt; Container:<br>  return pan + [ingredient]</pre><p>Assuming the pan is a list of ingredients that went into the soup this creates a new pan with the ingredient added. Similarly we can simmer and cut vegetables:</p><pre>@delayed<br>def simmer(pan: Container, time: Quantity) -&gt; Container:<br>  print(“simmering for {:~P}”.format(time))<br>  return pan</pre><pre>@delayed<br>def cut_vegetable(ingredient):<br>  return “sliced “ + ingredient</pre><p>Given these actions we can write down the recipe (in reduced form):</p><pre>def snert(pan):<br>  pan = add_vegetable(pan, “peas”)<br>  pan = simmer(pan, 60*units.min)<br>  veggies = cut_vegetable(“vegetables”)<br>  pan = add_vegetable(pan, veggies)<br>  pan = simmer(pan, 20*units.min)<br>  return pan</pre><p>Notice that each <em>action</em> is decorated with @delayed to tell Python that this is a task within a recipe. However the recipe itself is not decorated. Dask builds the recipe from the elemental actions that we provide it with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i7cNSfzKX9_dh4B3" /></figure><p>We can visualize the recipe in a <em>directed-acyclic-graph </em>(or DAG for short) by creating a node for each action, and an arrow for the data flow. In Dask this is done by calling snert([]).visualize().</p><p>We now have the recipe for snert in a more abstract form (a DAG), from which the parallelism that is inherent in the recipe is immediately visible.</p><h3>Our toy algorithm: π’s in the rain</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/0*Hc8vWedSy1mTOuw6" /></figure><p>In order to witness the advantages of parallelization we need an algorithm that is 1. parallelizable and 2. complex enough to take a few seconds of CPU time. In order to not scare away the interested reader, we need this algorithm to be understandable and, if possible, interesting. We chose a classical algorithm for demonstrating parallel programming: estimating the value of number π.</p><p>The algorithm we are presenting is one of the classical examples of the power of Monte-Carlo methods. This is an umbrella term for several algorithms that use random numbers to approximate exact results. We chose this algorithm because of its simplicity and straightforward geometrical interpretation.</p><p>Unfortunately, we have to start refreshing a couple of results from high school geometry. You probably remember that the area A of a square of side L is given by Aₛ = L², and the area of a circle of radius R is given by Aₒ = πR².</p><p>A circle of radius R can be stacked inside of a square of side L= 2R (see figure). The ratio between areas is thus, Aₒ/Aₛ=πR²/4R²=π/4.</p><p>This means that one possible (but very inefficient) way of estimating the number π is: π~4Aₒ/Aₛ.</p><p>We can now imagine the following mental experiment: if we let rain droplets fall in our figure, it is reasonable to expect the number of droplets inside the circle to be proportional to its area. The same is true for the square. Consequently, the ratio between the number of droplets inside the circle, M, and the number of droplets inside the square, N, should verify: π ~ 4M/N, where the approximation should become better as the number of droplets becomes higher.</p><p>An interactive version of the algorithm, used for teaching, can be found <a href="https://www.geogebra.org/m/mueUbwgg">here</a>.</p><h3>Implementation (in Python)</h3><p>Instead of using rain droplets, we’ll use a random number generator to simulate such a rain. In particular, we draw a coordinate <em>x</em> and a coordinate <em>y</em> from a uniform distribution, and use them as the coordinates a of a “droplet” impact.</p><p>Depending on your level of Python expertise, you might implement such an algorithm in different ways.</p><p>In an introductory Python course we could write this function as follows.</p><pre>import random</pre><pre>def calc_pi(N):<br>  M = 0</pre><pre>  for i in range(N):<br>    # Simulate impact coordinates<br>    x = random.uniform(-1, 1)<br>    y = random.uniform(-1, 1)<br> <br>    # True if impact happens inside the circle <br>    if x**2 + y**2 &lt; 1.0:<br>      M += 1</pre><pre>  return 4 * M / N</pre><p>This implementation has serious shortcomings when it comes to performance. We learn how to fix this in the second week of learning Python, when we encounter NumPy! We show here another way of implementing the same idea. In this case we are taking advantage of NumPy’s recommended vector notation. Used smartly, it avoids the need of for loops.</p><pre>import numpy as np</pre><pre>def calc_pi_numpy(N):<br>  # Simulate impact coordinates<br>  pts = np.random.uniform(-1, 1, (2, N))</pre><pre>  # Count number of impacts inside the circle<br>  M = np.count_nonzero((pts**2).sum(axis=0) &lt; 1)</pre><pre>  return 4 * M / N</pre><p>This implementation is a lot faster than the first one, but it still only uses a single processor. Surely, we can do better than that! We can parallelize this algorithm by running it several times and then computing the mean of the outputs.</p><p>The problem of computing π is representative of a family of problems known as <strong>embarrassingly parallel</strong>. Roughly, this means that parallelizing the algorithm <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel">should be easy</a>. If we want to use, say, 80000 random points, and we have 8 cores, we can split our problem in 8 problems of 10000 points each. This will give 8 different results, that we will collect together using a mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0UBFt5bQXeY2XnamffMC8w.jpeg" /><figcaption>The GIL</figcaption></figure><h3>The GIL</h3><p>There are many ways of parallelizing programs in Python, but not many of them are actually very good for problems like this. The reason is the Global Interpreter Lock or GIL. The GIL is infamous for killing any naive attempts at parallel programming in Python in its tracks.</p><p>The designers of Python chose ease-of-use over the use of power, a design principle that is in part responsible for the popularity of the language today. In the case of the GIL this means that any operation that requires interaction with the Python interpreter is locked to what is effectively a single thread. Multi-threading in Python is useful only for doing IO operations or native function calls that resolve outside the ever present eye of the Python interpreter. There are two solutions to this problem: running multiple Python instances or doing all of your work outside of Python.</p><p>For a lot of small-scale parallel work, running multiple instances of Python is not a very good solution: there is the overhead of copying data between the different Python instances. We can do better than this! <strong>What if we just kill the GIL?</strong> We’ll see soon that the package Numba allows us to do it easily by just using a decorator in our function. We can then use any other tool for parallelizing Python to run the algorithm in parallel, in this case: Dask.</p><p>One way of using Dask is through its NumPy-esque daskarray interface. This will give some speedup because the underlying NumPy routines are not choked by the GIL. However, we can do a lot better if we eliminate the GIL entirely using Numba.</p><h3>Let’s do it</h3><p>First, we want to know how many cores we have. In Python this can be easily figured out easily using the multiprocessing package:</p><pre>import multiprocessing<br>ncpus = multiprocessing.cpu_count()<br>print(“We have {} cores to work on!”.format(ncpus))</pre><p>Now, we use Numba to comfortably avoid the GIL by simply using the @jit decorator around our function. Numba compiles the Python code to native machine code to make it perform faster. We have to forget what we learned about using NumPy here.</p><pre>from numba import jit</pre><pre>@jit(nopython=True, nogil=True) # Required to kill the GIL<br>def calc_pi_nogil(N):<br>  M = 0</pre><pre>  for i in range(N):<br>    # Simulate impact coordinates<br>    x = random.uniform(-1, 1)<br>    y = random.uniform(-1, 1)<br> <br>    # True if impact happens inside the circle <br>    if x**2 + y**2 &lt; 1.0:<br>      M += 1</pre><pre>  return 4 * M / N</pre><p>Ironically, our implementation is identical to the first very slow Python version, with the exception of the @jit line!</p><p>We set out multiple jobs for computing π and take the mean of the results.</p><pre>from dask import delayed</pre><pre>@delayed<br>def mean(*args):<br>  return sum(args) / len(args)</pre><pre># Call calc_pi_nogil 10 times with N = 10 million<br>x = mean(*(delayed(calc_pi_nogil)(10**7) for i in range(10)))</pre><p>The workflow can be visualized using:</p><pre>x.visualize()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6L0LJBssxYOlRJzF" /><figcaption>A recipe for computing π faster</figcaption></figure><p>And evaluated using:</p><pre>x.compute()</pre><p>Try it out yourself! Fire up a Jupyter notebook, pip install dask numba, and you’re good to go.</p><blockquote>Erratum 2020/01/16: There are some issues with the code presented in this post, these are largely due to Medium replacing double quotes with unicode characters. A functioning example code is available in this Gist:</blockquote><blockquote><a href="https://gist.github.com/jhidding/e08c3096b5c54bf2138ca248625de029">https://gist.github.com/jhidding/e08c3096b5c54bf2138ca248625de029</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fd62c90217d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/parallel-programming-in-python-7fd62c90217d">Parallel programming in Python</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why all you’ll ever need is Markdown]]></title>
            <link>https://medium.com/escience-center/why-all-youll-ever-need-is-markdown-dc604f0ab309?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc604f0ab309</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[scientific-writing]]></category>
            <category><![CDATA[web-content-writing]]></category>
            <category><![CDATA[document-converter]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 07:01:02 GMT</pubDate>
            <atom:updated>2019-07-02T07:57:13.721Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>an introduction to Pandoc</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4G2GgU10iJkPldd1" /><figcaption>Photo by <a href="https://unsplash.com/@d_mccullough?utm_source=medium&amp;utm_medium=referral">Daniel McCullough</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Markdown is widely used for writing up documents. It is supported by many blog engines, GitHub readme, you name it. There are many varieties, dialects and extensions to Markdown. The standard is described on the <a href="https://daringfireball.net/projects/markdown/">Daring Fireball website</a>. One place where many flavours of Markdown meet is in <a href="https://pandoc.org/">Pandoc</a>. Pandoc can convert Markdown to many different formats like HTML, LaTeX, PDF (through LaTeX), RTF, DOC, EPUB and even back to Markdown of a different flavour. There are some little known features (or extensions) of Markdown that make it very versatile and suitable for any rich text content, especially if you use Pandoc.</p><p>The take-away message is: you will never again have to write a document in LaTeX or HTML directly, not for writing notes, reports or papers, no power-point for presentations, no awkward wysiwig editor for web content (I’m talking to you Medium!); just use Markdown.</p><p>You might ask “But Johan, how do I then …?”, shush! The answer is always going to be: <strong>Pandoc</strong>.</p><h3>Primer</h3><p>Markdown is a way of writing up rich content (i.e. text, document hierarchy, images, lists, quotes, etc.) in plain text using a human readable format. The format is aimed to mimic in plain text the formatted result:</p><pre>Level 1 Header<br>==============</pre><pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do <br>eiusmod tempor incididunt ut labore et dolore magna aliqua.</pre><pre>Level 2 Header<br>--------------</pre><pre>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris <br>nisi ut aliquip ex ea commodo consequat.</pre><pre>* list item<br>* Another item</pre><pre>## Also a Level 2 Header</pre><pre>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</pre><pre>&gt; quote: Excepteur sint occaecat cupidatat non proident, sunt in <br>&gt; culpa qui officia deserunt mollit anim id est laborum</pre><p>You can read <a href="https://daringfireball.net/projects/markdown/syntax">Daring Fireball</a> for more syntax. The basics of Markdown are highly intuitive, but in many instances standard Markdown does not suffice: there is no support for equations, citation management, cross references or numbered figures. However, Pandoc supports many extensions and flavours of Markdown that have evolved over the years. Markdown feels a bit like a natural language. This has lead to some <a href="https://www.ericholscher.com/blog/2016/mar/15/dont-use-markdown-for-technical-docs/">critique on the use of Markdown in technical documents</a>.</p><p>I will highlight some extensions, all clearly documented and supported by Pandoc, that transform Markdown into a versatile and extendable format, suitable for even the most technical and demanding documents, yet easy to use when no such demands arise.</p><h4>Flavours and extensions</h4><p>There are many extensions to Markdown, some of which are more widely used than others. One of the most influencial flavour of Markdown is the superset by Github, its major addition being that of delimited code blocks.</p><pre>```javascript<br>var factorial = n =&gt; (n &lt; 2) ? 1 : n * factorial(n — 1);<br>```</pre><h4>Attributes</h4><p>Nothing good ever comes from PHP, except for PHP Markdown, which adds attributes to Markdown.</p><p>Any element in a Markdown document can be adorned with (CSS style) attributes by appending them in curly braces: {#id .class .class key=value}. For example,</p><pre>## The proof {#proof .section color=red}</pre><p>when converted to HTML looks like</p><pre>&lt;h2 id=&quot;proof&quot; class=&quot;section&quot; color=&quot;red&quot;&gt;The proof&lt;/h2&gt;</pre><p>or to LaTeX</p><pre>\hypertarget{proof}{%<br>\subsection{The proof}\label{proof}}</pre><p>In the case of LaTeX, the color attribute as well as the class is ignored, because Pandoc (by default) doesn’t know what to do with it. The #proof id attached to this header can be used further on in the document to make cross-references.</p><p>The attribute syntax also applies to code blocks: a line starting with ```python is equivalent to ``` {.python} .</p><h4>DIV elements</h4><p>A &lt;div&gt; element can be added using three (or more) colons.</p><pre>::: {.warning}<br>This is a warning!<br>:::</pre><p>This can be used to write down any non-standard element. So how is this rendered? If your output format is HTML, change the style sheet. For generating LaTeX however we need to do a bit more work. This is where Pandoc comes in. Pandoc has support for filtering elements and creating relevant output, but we’ll get back to that.</p><h4>YAML metadata</h4><p>Information that is usually contained in a HTML &lt;header&gt; region can be included in the YAML metadata block. This is a block delimited by hyphens at the top of the document.</p><pre>---<br>title: A theorem on right angled triangles<br>author: Pythagoras of Samos<br>date: ~520 BC, a hot summer night<br>---</pre><p>This is also the place where you can configure options for Pandoc and its filters.</p><h4>Citations</h4><p>Citations are managed using the pandoc-citeproc plugin. For those who have worked with BibTeX (or another bibliography database) before, you include the bibliography by adding a line to the YAML header block. Say you have stored your references in ref.bib , and want to create a dedicated section called “References” to list the citations:</p><pre>---<br>bibliography: ref.bib<br>reference-section-title: References<br>---</pre><p>There are many ways to cite papers, the syntax for which is <a href="https://pandoc.org/MANUAL.html#citations">documented in the Pandoc manual.</a> Basic citation looks like [@Hidding2014] , where Hidding2014 is an entry in the bibliography. Several editors (VSCode and Emacs) even support autocompletion on the included bibliography.</p><h4>Equations</h4><p>Equations can be entered using the famous LaTeX DSL for equations. Use single $ characters to delimit an inline equation and double $$ to delimit a full width equation.</p><pre>Given a right angled triangle of sides $a$, $b$ and hypotenuse $c$, we may state that,</pre><pre>$$a^2 + b^2 = c^2.$$</pre><p>When converting to a LaTeX based output this will work trivially. For HTML it is probably best to use MathJax, enabled in Pandoc with the --mathjax and --standalone flags.</p><p>I promised to show you how Markdown can be extended with arbitrary functionality using Pandoc. It is inevitable that I will get a bit more technical here, but the rewards are high.</p><h3>Pandoc basics</h3><p>Pandoc reads and writes documents of many formats. It does so by converting to and from a native intermediate representation.</p><p>We’ll create a document named last-theorem.md and enter the following:</p><pre>---<br>title: Last theorem<br>author: P. de Fermat<br>---</pre><pre>For integer values of $a$, $b$, $c$ and $n &gt; 2$, the equation</pre><pre>$$a^n + b^n = c^n,$$</pre><pre>has no solution. I have a truly remarkable proof for this.</pre><p>We can see how Pandoc reads a document by running</p><pre>pandoc -f markdown+yaml_metadata_block -t native -s last-theorem.md</pre><p>which will give (slightly edited for readability)</p><pre>Pandoc<br> (Meta {unMeta = fromList<br>   [(“author”, MetaInlines [Str “P.”,Space,Str “de”,Space,Str “Fermat”])<br>   ,(“title”, MetaInlines [Str “Last”,Space,Str “theorem”])]})<br> [Para [Str “I”,Space,Str “state”,Space,Str “that,”,Space<br>       ,Str “for”,Space,Str “integer”,Space,Str “values”,Space<br>       ,Str “of”,Space,Math InlineMath “a”,Str “,”,Space<br>       ,Math InlineMath “b”,Str “,”,Space<br>       ,Math InlineMath “c”,Space,Str “and”,Space<br>       ,Math InlineMath “n &gt; 2”<br>       ,Str “,”,Space,Str “the”,Space,Str “equation”]<br> ,Para [Math DisplayMath “a^n + b^n = c^n,”]<br> ,Para [Str “has”,Space,Str “no”,Space,Str “solution.”,Space<br>       ,Str “I”,Space,Str “have”,Space,Str “a”,Space<br>       ,Str “truly”,Space,Str “elegant”,Space,Str “proof”<br>       ,Space,Str “for”,Space,Str “this,”,Space,Str “but”,Space<br>       ,Str “this”,Space,Str “is”,Space,Str “not”,Space<br>       ,Str “the”,Space,Str “place”,Space,Str “to”,Space<br>       ,Str “give”,Space,Str “it.”]]</pre><p>Yes, this is <a href="https://haskell.org/">Haskell</a> syntax. It just means what you think it means. Using native output in Pandoc will be very useful if you start developing your own filters. For now it just serves to illustrates how Pandoc works. If you’re not a hacker, you’ll never have to look at this again 🤓👍.</p><p>Let’s create a PDF from this mathematics wizardry.</p><pre>pandoc -f markdown+yaml_metadata_block -t latex -o last-theorem.pdf -s last-theorem.md</pre><p>Resulting in a nice PDF rendering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5CzmUE-GndA7H9_l0vAFQ.png" /><figcaption>Typeset paper on a famous theorem</figcaption></figure><h4>Pandoc filters</h4><p>There is a big problem with the above example. The equation is not numbered! Pandoc filters let you change the intermediate representation. Let’s try the <a href="https://github.com/tomduck/pandoc-eqnos">pandoc-eqnos</a> filter. This filter is written in Python (using pypandoc); any language that can read the intermediate JSON representation works.</p><pre>pip install --user pandoc-eqnos</pre><p>We’ll need to change the last-theorem.md document a bit. To get an equation numbered, add an id to the equation.</p><pre>$$a^n + b^n = c^n,$$ <strong>{#eq:fermat}</strong></pre><p>Also add a sentence to the end.</p><pre>The prove of inexistence of a solution for <strong>Equation @eq:fermat</strong> had eluded mathematicians for centuries.</pre><p>Now to invoke the equation numbering filter, add the --filter pandoc-eqnos argument to the command line.</p><pre>pandoc -f markdown+yaml_metadata_block -t latex <strong>--filter pandoc-eqnos</strong> -o last-theorem.pdf -s last-theorem.md</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kt-38FBpJoz_V1RdJj9odQ.png" /><figcaption>Typeset paper on a famous theorem with numbered equations</figcaption></figure><p>Pandoc command lines can grow out of hand rather quickly. It is advisable to manage your Pandoc settings in a Bash script or Make file, whatever you prefer.</p><h4>Lua filters</h4><p>Pandoc has built-in support for filters written in Lua. Filters written in Lua are generally faster than those written in Python or other external languages. Lua filters forego documents being passed to an external program via JSON, but rather work directly on the abstract syntax tree as it is represented in Pandoc itself.</p><p>Let’s add a feature. Add the following to our budding math paper:</p><pre>::: {.warning}<br>Modular forms and elliptic curves ahead!<br>:::</pre><p>To parse this, Pandoc needs the extension fenced_divs enabled.</p><pre>pandoc -f markdown+yaml_metadata_block<strong>+fenced_divs</strong> --filter pandoc-eqnos -t native -s last-theorem.md</pre><p>At the end of the output will be the expression:</p><pre>Div <br> (“”,[“warning”],[])<br> [Para [Str “Modular”,Space,Str “forms”,Space,Str “and”,Space<br> ,Str “elliptic”,Space,Str “curves”,Space,Str “ahead!”]]</pre><p>Once we generate HTML from this example, we can add the proper CSS to the .warning class to change the looks of the warning. However, in the generated PDF there’s no change. Let’s make a filter that creates a nice coloured box in the LaTeX output. We define a filter that runs on all Div elements in the file warning-div.lua .</p><pre><strong>function</strong> Div(el)<br>  <strong>if</strong> el.classes[1] == &quot;warning&quot; <strong>then</strong><br>    <em>-- insert element in front</em><br>    table.insert(<br>      el.content, 1,<br>      pandoc.RawBlock(&quot;latex&quot;, &quot;\\begin{warning}&quot;))<br>    <em>-- insert element at the back</em><br>    table.insert(<br>      el.content,<br>      pandoc.RawBlock(&quot;latex&quot;, &quot;\\end{warning}&quot;))<br>  <strong>end</strong><br>  <strong>return</strong> el<br><strong>end</strong></pre><p>The filter checks if the div has class warning , if so, it adds a LaTeX RawBlock at the start and end of the div .</p><p>Running Pandoc with --lua-filter=warning-div.lua now converts the div element to a LaTeX string</p><pre>\begin{warning}<br>Modular forms and elliptic curves ahead!<br>\end{warning}</pre><p>This is not standard LaTeX, so we’ll need to define a macro in warning.tex</p><pre>\usepackage{tcolorbox}<br>\newenvironment{warning}<br>    {\begin{tcolorbox}[colbacktitle=red!50!white,<br>                       title=Warning,coltitle=black,<br>                       fonttitle=\bfseries]}<br>    {\end{tcolorbox}}</pre><p>We can run Pandoc again to generate the PDF. The -H option can be used to include files into the generated output.</p><pre>pandoc -f markdown+yaml_metadata_block+fenced_divs --filter pandoc-eqnos <strong>--lua-filter warning-div.lua</strong> <strong>-H warning.tex</strong> -t latex -o last-theorem.pdf -s last-theorem.md</pre><p>Did I mention Pandoc command lines tend to grow out of hand?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FIsZuEJ8O4AzlMpB3ARGw.png" /><figcaption>Typeset paper on a famous theorem with numbered equations and a warning</figcaption></figure><h3>Skies and limits</h3><p>Granted, to unlock the full power of Markdown for the web, you’ll need to know some HTML and CSS, and to tweak PDF output to your impossibly high standards you need to grok LaTeX. All the more reason to create an ecosystem of scripts, themes and tutorials to ease the learning curve. Also, code editors should offer better support for more varieties of markdown. I don’t mean cluttering up the editing experience with more distracting tool-tips, snippets etc. Just this: correct and efficient highlighting and proper outline support.</p><p>This was just a teaser of what is possible with Pandoc. Did I mention creating slide shows with reveal.js ? Or how about doing some literate programming with entangled <a href="https://blog.esciencecenter.nl/entangled-1744448f4b9f">(see my previous post on that)?</a> The documentation of Pandoc is excellent, so just go ahead and write all your content in Markdown!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc604f0ab309" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/why-all-youll-ever-need-is-markdown-dc604f0ab309">Why all you’ll ever need is Markdown</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking the barrier: fluid simulations parallel-in-time.]]></title>
            <link>https://medium.com/escience-center/breaking-the-barrier-fluid-simulations-parallel-in-time-bbc7d38a5d16?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc7d38a5d16</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[numerical-methods]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Mon, 03 Jun 2019 09:30:47 GMT</pubDate>
            <atom:updated>2019-06-03T09:30:47.190Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgHps8C6sIPJ87U5" /><figcaption>Parallel flows — Photo by <a href="https://unsplash.com/@sickle?utm_source=medium&amp;utm_medium=referral">Sergey Pesterev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>These days computers are growing faster only by adding more cores and increasing parallelism of the programs. As an example, suppose we are computing the turbulent flow around an airfoil. This is a problem that is very intensive to compute so we’d want to parallelise it.</p><h4>Parallel-in-space, and scaling of overhead</h4><p>The traditional approach is to divide the volume of our simulation into different domains, and give each domain to a different processor. After each time-step the changes in each domain need to be communicated between the processors. This adds overhead to the computation. Each time we split the volumes in half we can potentially double the speed in which we get our answer, but this is mitigated by the fact that we also increase the amount of communication needed between the compute nodes.</p><p>This principle of balancing processing power versus communication overhead is a universal one. There always seems to be a barrier to how many processors we can use for solving a problem. The question is then, <em>how can we break this barrier</em>, how can we parallelise our computation even further? This is the point where we go parallel-in-time.</p><h4>Parallel-in-time, but how?</h4><p>At first the notion of parallel-in-time integration often is counter intuitive. The problem of simulation a fluid (and many other computations like it) is inherently sequential. <strong>The change in a state of a physical system always depends on the current state of the system.</strong> How then, do we compute the future in parallel with the past?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ex_5x8X3ahx9H8tr" /><figcaption>One state follows the other — Photo by <a href="https://unsplash.com/@oratnin?utm_source=medium&amp;utm_medium=referral">Kumiko SHIMIZU</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Parareal</h3><p>A simple method that, in theory, gives decent speed-ups is <a href="https://en.wikipedia.org/wiki/Parareal">Parareal</a>. It was invented in 2001 by <a href="https://doi.org/10.1016%2FS0764-4442%2800%2901793-6">Lions, Maday &amp; Turinici</a>. The introduction of Parareal was largely what got the current surge in parallel-in-time methods started, since it is the first algorithm that showed enough promise to give a real speed up. Also, it is relatively simple to explain.</p><h4>Coarse &amp; Fine</h4><p>Parareal works by defining a c<em>oarse</em> and a <em>fine</em> algorithm. The coarse algorithm should be cheap to compute, possibly a low order integration, on a coarse grid, possibly also with reduced model complexity and with a large time-step. The <em>fine</em> integrator on the other hand, is the expensive algorithm often computed on a finer grid, with all necessary physics included.</p><p>The first step of Parareal is to get an initial guess for the evolution of the system by taking the result of just the coarse integrator. We use this initial guess to start the fine integrator at each time-step simultaneously. Since we already have an initial guess for each time-step (on the coarse grid), we can perform the fine integration in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MIbMvMtZ8iDrIh39" /><figcaption>Coarse building with fine grid — Photo by <a href="https://unsplash.com/@lanceanderson?utm_source=medium&amp;utm_medium=referral">Lance Anderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At the end of this step each of the fine integrators will be slightly off, because they started from a wrong first estimate. We can try to correct the results of the fine integrators. Several iterations of fine integration followed by correction will be needed.</p><p>The quality of the Parareal algorithm depends heavily on the accuracy of the coarse integrator.</p><p>We only get a speed-up if the algorithm converges in fewer iterations than our number of time-steps. Also note that while we get our answer faster, we need to do a lot more work to get it.</p><h4>The Bay of Fundy</h4><p>An example of a successful application of Parareal in hydrodynamics was presented by <a href="http://doi.org/10.1016/j.jocs.2016.12.006">Eghbal, Gerber &amp; Aubanel (2016) [doi:10.1016/j.jocs.2016.12.006]</a>. They implemented Parareal on top of an existing (proprietary, sad enough) GPU hydro code with the aim of modelling hydro turbine tidal power generation in the Bay of Fundy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTqna61llKW59pGAbDslWg.jpeg" /><figcaption>(left) Simulation of tidal flow in Bay of Fundy (right) Gantt chart of Parareal, the number in each box signifies the time-step that is worked on. Processor 0 performs the coarse integration and orchestrates the other processors. (from Eghbal et al 2016)</figcaption></figure><p>The Gantt chart on the right shows the work being done by 10 processors. Eghbal et al. divided the work in multiple time ‘windows’, two of which are shown here. In each window we see that Parareal converged in 5 iterations. To save data transfer in the correction step, each processor works on successive time-steps. This way only the data of the coarse integrator has to be propagated between processors.</p><h4>Difficulties</h4><p>One area where Parareal is reported to go wrong is with oscillating systems. The coarse integrator usually gives a result that is out-of-phase with the real solution. Attempts have been made to do phase-correction on top of Parareal, but this is still very much a topic of research.</p><h4>Beyond Parareal</h4><p>There are many more methods for parallel-in-time integration. One example is <em>Multigrid Reduction in Time </em>or MGRIT. MGRIT can be seen as a generalisation of Parareal. It has more flexibility in the ways to correct the results from the fine integrator, and can be used in conjunction with multi-grid method in space. An implementation of MGRIT is available in the XBraid package.</p><h3>Fair warning</h3><p>There are reports of significant speed-ups with parallel-in-time methods but this comes with a warning. There is a big investment into tuning the system. A lot of work goes into making current parallel-in-time methods perform faster than sequential methods. In the case of Parareal, this means finding a good model for the coarse integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G1X_X13MDVRAqNAz" /><figcaption>Effects of overheating — Photo by <a href="https://unsplash.com/@bearthor?utm_source=medium&amp;utm_medium=referral">Bjørn Tore Økland</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Stay green</h4><p>To recap, our question was: How do we compute past and future in parallel? The answer: by wasting a lot of computational power. In these days of ecological responsibility and green computing, wasting valuable processor cycles seems like a bad idea. Even if you succeed in getting a speed-up, you still need to convince your local super computing facility why you need all this.</p><p>We may find however, that in some cases there is no other way forward. As the number of cores on a machine keep increasing, we need to be more creative in utilizing the computational power we’re given.</p><h4>Further reading</h4><p>The field of parallel-in-time methods is still young. At <a href="http://www.parallel-in-time.org/"><em>http://www.parallel-in-time.org</em></a> there is a collection of scientific papers and computer codes. A good review on available methods is <a href="https://www.youtube.com/watch?v=dn5vqN8ezuE">“50 years of parallel-in-time” by Martin Gander</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc7d38a5d16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/breaking-the-barrier-fluid-simulations-parallel-in-time-bbc7d38a5d16">Breaking the barrier: fluid simulations parallel-in-time.</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[enTangleD]]></title>
            <link>https://medium.com/escience-center/entangled-1744448f4b9f?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/1744448f4b9f</guid>
            <category><![CDATA[literateprogramming]]></category>
            <category><![CDATA[open-science]]></category>
            <category><![CDATA[scientific-method]]></category>
            <category><![CDATA[programming-tools]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 07:07:42 GMT</pubDate>
            <atom:updated>2022-05-09T09:36:39.491Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4><strong>a bi-directional Literate Programming tool</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzRmbKxAvetqVm7znEY8Sw.jpeg" /><figcaption>© Alessandra Sequeira, Entanglement (<a href="http://sinapsisequeira.blogspot.com/">http://sinapsisequeira.blogspot.com/</a>)</figcaption></figure><p>I present <em>enTangleD</em> (<a href="https://entangled.github.io/">github.io pages</a>), a tool for pain free literate programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eN_G62FYBlXK3FUDIheAA.jpeg" /><figcaption>Donald Knuth</figcaption></figure><p>There’s no way I can write about literate programming not starting at the source: Donald Knuth, the great master and chief, writer of “The Art of Computer Programming”, “Surreal Numbers” and inventor of <em>literate programming</em>. He coined this term somewhat maliciously, thinking that “nobody wants to admit writing an <em>illiterate</em> program”. So what is literate programming?</p><p>Knuth considers code as a way of communicating with a computer. As you write code you are <em>teaching</em> the computer how to perform a certain task. However, many times when you’re programming, you’re not just teaching the computer. You are also teaching your (very human) peers. This is why so many teachers drone on about:</p><ul><li>clean code</li><li>simple solutions</li><li>extensive documentation</li></ul><p>Literate programming goes much further than that. A literate program is a program that can be read as a work of literature. Specifically, we write the <em>entire </em>program as a document (be it Markdown, Org-mode or LaTeX) explaining what the program does and how this is implemented in plain English. The actual implementation, in whatever language you may prefer, is sprinkled around in the form of code blocks. For those who are familiar with Jupyter notebooks, or the notebook interface to Mathematica: notebooks can be considered a form of literate programming, but there are differences which we will discuss later on.</p><p>An example of how a woven literate program looks can be found in my numerical code to compute cosmological structure formation <a href="https://jhidding.github.io/adhesion-code/">“Computing the adhesion model using C++ and CGAL”</a> (<a href="https://doi.org/10.5281/zenodo.1477536">DOI:10.5281/zenodo.1477535</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pctd-x7jhr6iOnt-QmCIeg.png" /><figcaption>Screenshot of woven literate code.</figcaption></figure><p>The principles underlying literate programming, merely prudent in most circumstances, become essential once we consider writing and publishing code for the scientific community, for several reasons.</p><ul><li><strong>scientific meticulousness:</strong> Scientific works are supposed to be held to exacting standards. These standards are upheld by systems of peer-review and demands of precise reporting of methodology. These standards are often surprisingly lax when it concerns the use of software. This problem is for a large part addressed by the “Open Science” movement in general, stimulating the use of open source software in science. Still, even if code is open source, this does not mean that this code can be easily understood.</li><li><strong>epistemology:</strong> Epistemology is the theory of <em>knowledge </em>and part of the philosophy of science. When can we say we know something? When was the theory of relativity born? Was it when Einstein woke up after having a dream about trains, mirrors and flashlights, or after he successfully wrote his theory down in such a way that one other person could understand it? Think about it.</li><li><strong>programming literacy:</strong> Scientists create a lot of computer code, but are, in general, not professionally trained programmers. This increases the need for exposure to each others code. Literate programming stimulates other people to actually read your code, while you’ll have an easier time reading other people’s code. This interaction should make better programmers of all of us.</li></ul><p>Knuth developed a system called <em>WEB</em> for annotating TeX with the relations between the different code blocks. <em>WEB</em> came with two tools: <em>tangle</em> and <em>weave</em>. The <em>tangle</em> tool takes the literary source, parses the <em>WEB</em> references therein and pastes together traditional source files that can be subsequently compiled into a working binary. <em>Weave</em> converts the (annotated) TeX source into a secondary TeX that is ready for type setting and publishing. We will refer to these programs as the <em>tangler</em> and <em>weaver</em>.</p><p>There is a practical issue with this form of literate programming. We’re having the true source code in a different place than the compiler, debugger and IDE think it is, and this breaks the usual development cycle. If one were to develop a system for literate programming today, it would look a bit different. I will now explain a Markdown based system and present a tool called <em>enTangleD</em> that makes the development cycle of literate programs a smoother experience.</p><h3>Literate programming in Markdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Vcp-iI0RG5iIsgZxrSK4AA.jpeg" /><figcaption>© Alessandra Sequeira, Inner Foliage (<a href="http://sinapsisequeira.blogspot.com/">http://sinapsisequeira.blogspot.com/</a>)</figcaption></figure><p><a href="https://daringfireball.net/projects/markdown/">Markdown</a> has become a standard way of expressing text documents (without there being a standard and moreover many different flavours). Markdown can be converted to HTML, LaTeX and many other formats. Everyone’s favourite tool for markdown conversion is of course <a href="https://pandoc.org/">PanDoc</a>. One guiding principle in the following design is that the resulting Markdown is parsable by PanDoc. We will be denoting code blocks using three back ticks on the opening and closing line of the code block like so:</p><pre>```py<br>print(&quot;Hello, Amsterdam!&quot;)<br>```</pre><p>One way of denoting the programming language of the code block is by extending the opening back ticks with an accepted abbreviation of the language. In the above example we tell the document formatter that the given source code is written in Python. For our purpose this syntax is not flexible enough. We want to extend the code block meta-data with other properties. PanDoc supports attaching a CSS class, id and attributes to code blocks using curly brackets:</p><pre>``` {.py file=hello.py}<br>print(&quot;Hello, World!&quot;)<br>```</pre><p>In this system of literate programming the tangler will extract this code block and write it to a file `hello.py`. More complicated programs can be built using a system of references. Keeping with Python, it is considered good form to enclose a main script using the following `if`-statement:</p><pre>``` {.py file=hello2.py}<br>if __name__ == &quot;__main__&quot;:<br>    &lt;&lt;main-body&gt;&gt;<br>```</pre><p>We can define the body anywhere else in the document:</p><pre>``` {.py #main-body}<br>print(&quot;Hello, Universe!&quot;)<br>```</pre><p>The tangler will then combine these code blocks into a single file:</p><pre>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Hello, Universe!&quot;)</pre><p>The system of references allows us to decompose a program into literary parts, putting the code in a didactic narrative.</p><h3>enTangleD</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*s724R83u1MtKlug5I9wL0w.jpeg" /><figcaption>© Alessandra Sequeira, Inner Shadow (<a href="http://sinapsisequeira.blogspot.com/">http://sinapsisequeira.blogspot.com/</a>)</figcaption></figure><p>As I mentioned before, there is a practical problem with developing software in the way I described above. All our code is in one or more Markdown files. If we want to build it, we first have to tangle, then, if we work with a compiled language, compile, hope that nothing goes wrong and run. But what if we have compiler errors, or worse, the program compiles but doesn’t give the expected output? We then enter the usual edit-compile-debug cycle. The source files that we work on were generated by the tangler and it makes no sense editing them directly. In comes <em>enTangleD</em>! The D stands for <em>daemon</em>.</p><p><em>enTangleD</em> monitors both the Markdown and the generated source files for changes. If a source file changes, the corresponding code blocks in the Markdown are updated accordingly, and the other way around. To make this work, <em>enTangleD</em> writes the source code with commented markers telling the daemon where in the Markdown file the code comes from.</p><h3>Alternatives</h3><p>There exist alternatives to our Markdown based literate programming model:</p><ul><li><strong>Jupyter:</strong> <a href="https://jupyter.org/">Jupyter</a> gives you an interactive notebook environment for any language that has a Jupyter kernel written (there are many). Advantages are: interactivity, inline graphing, good for experimentation. Disadvantages: Jupyter notebooks do not play well with git version control, the interactivity also doesn’t play well with compiled languages and lastly provenance is not guaranteed since the order of cell-execution is not fixed. Jupyter is awesome, but it is not perfect.</li><li><strong>literate Haskell:</strong> Haskell programmers write their papers in <em>literate Haskell</em>. This is very fine for Haskell. <em>enTangleD</em> is completely language agnostic.</li><li><strong>Pweave</strong>, <strong>Weave.jl</strong>, <strong>Racket Scribble</strong>, etc: these are all language specific.</li><li><strong>Org-mode:</strong> if your editor of choice is Emacs and your document is only supposed to be opened by like-minded people, Org-mode is the awesomest ;). Still, it does not support bi-directional tangling.</li></ul><h3>Try it yourself!</h3><p>Try <em>enTangleD</em> for yourself! <em>enTangleD</em> is written in Haskell and source code is hosted on <a href="https://github.com/jhidding/entangled">GitHub</a>. The repository also contains an example Markdown file containing source code for an over-engineered C++ implementation of <a href="https://jhidding.github.io/enTangleD/99-bottles.html">“99 bottles of beer”,</a> and a small browser game called <a href="https://jhidding.github.io/enTangleD/slasher.html">“Slasher”</a> which is <a href="https://jhidding.github.io/enTangleD/elm-slasher.html">implemented in Elm</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1744448f4b9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/entangled-1744448f4b9f">enTangleD</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easier Docker in Python]]></title>
            <link>https://medium.com/escience-center/easier-docker-in-python-3993cb12e906?source=rss-ee75caffdf66------2</link>
            <guid isPermaLink="false">https://medium.com/p/3993cb12e906</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[escience]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[scientific-software]]></category>
            <dc:creator><![CDATA[Johan Hidding]]></dc:creator>
            <pubDate>Fri, 03 Feb 2017 10:09:12 GMT</pubDate>
            <atom:updated>2017-02-15T16:28:26.787Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68X2g8ziJ_aHdtiHqajr3Q.jpeg" /></figure><p><a href="https://www.docker.com/">Docker</a> is a tool that creates a stack of virtual environments on top of a running Linux kernel. This allows you to run tools (and web services) in an encapsulated environment. I use Docker to call binary codes from Python in the context of a broader scientific/computational workflow. Using docker containers for this makes it infinitely easier to share the results of such a workflow. There is a <a href="https://docker-py.readthedocs.io/en/stable/">Python module</a> for the API, but this is not the easiest to use, certainly not as easy as the docker command-line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*ChkdKbYyM7mIITvaUkHaDw.jpeg" /><figcaption>Exterminate!</figcaption></figure><p>So, my goal is to make an easy interface to Docker that allows me to:</p><ol><li>create a container</li><li>upload some input files</li><li>run one or more commands</li><li>retrieve results</li><li>exterminate!</li></ol><p>A Docker container can be thought of as a virtual machine, sharing resources with other containers that run on the same image. When we have a container running, we can communicate with it by sending it commands, talking to services and we can read or write to the file system. This last action is performed through tar archives.</p><p>All of this makes a Python program that uses Docker directly through the <a href="https://docker-py.readthedocs.io/en/stable/">docker module</a> rather unreadable. Here, I show an example of how to fix this situation using only small amounts of additional Python code. If you like to play with this example, <a href="http://github.com/jhidding/easy-docker.py">get the code in this post from github</a>.</p><p>In the spirit of <a href="https://blog.thesoftwarecraft.com/2013/11/wishful-programming.html">wishful programming</a>, I show how we can express a simple Docker session after all this is complete. Usually a docker container contains one or more binary packages that provide some service; to keep this example minimal, we use the BusyBox container which has a very small footprint (the download is less than 1MB!). This example decrypts a secret message using Sed. Sed stands for Stream Editor; it is present on any decent Unix system, and used primarily to extract data from text files. The script used here was taken from the great <a href="https://rosettacode.org/wiki/Rot-13#AWK">Rosetta Code</a> website.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3625f483cf4effd5b787e062789a8696/href">https://medium.com/media/3625f483cf4effd5b787e062789a8696/href</a></iframe><p>I introduced two classes to make this example work: Archive and DockerContainer. The Archive class handles the construction of a tar-ball, while the DockerContainer class manages the communication with the Docker daemon. By implementing this last class as a <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/">context-manager</a>, the Docker container is removed immediately after we are done with it, hence no need for Daleks on that account.</p><p>Note that the Archive.add_text_file methods returns self. This is good behaviour for methods that only modify an existing object, since it allows chaining these methods and assigning the end result of this chain of method calls in one statement.</p><p>This example code is concise and only focuses on <em>what</em> we intend to do, not <em>how</em> we make Docker understand. You could open a shell, copy the above sed-script and message into individual files and run the script using the same commands that you already see.</p><p>Let’s start with a nicer interface to create a tar-ball. Docker uses tar-files to communicate data, so that multiple files can be transmitted in a single stream. Python has a built-in module for creating tar-files, however we are not interested in actually storing the file anywhere. We just need the data in a buffer so that we can send it to Docker with no further ado. This is why the tarfile.open function is passed an instance of io.BytesIO. This last class acts like a normal file, however it just stores in memory, not on disk.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64cbab87aed6c4890f52920d4496fab7/href">https://medium.com/media/64cbab87aed6c4890f52920d4496fab7/href</a></iframe><p>Next, the Docker container. Most of this code is just an object-oriented wrapper around the Python Docker SDK. The interface in the SDK is spartan by choice. Every user has different needs; rather than cater to every one of those, the Docker team chose to offer a very thin layer around the HTTP API. This is a <em>good thing</em>. It just means we have to try a bit harder to write good code with it.</p><p>The DockerContainer class presented here has the nice feature that it optionally stores a working directory in self.working_dir, which reflects the given working_dir when the container was started. If the user tries to add files with a relative target path (in stead of an absolute one, that start with /), the working_dir is automatically joined with the given path.</p><p>The DockerContainer.run method is made to reflect the native Python subprocess.run superficially. This makes its use much easier to remember!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1908109a60d843a5617b6922a6a15f43/href">https://medium.com/media/1908109a60d843a5617b6922a6a15f43/href</a></iframe><p>Right at the end, the __enter__ and __exit__ methods implement the so called context-manager, allowing the use of with DockerContainer(...) as c: etc. If you’ve never seen that before, do read <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/">this post</a> by Jeff Knupp, or the <a href="https://www.jeffknupp.com/writing-idiomatic-python-ebook/">Idiomatic Python</a> book by the same author!</p><p>I hope to have convinced you that with just a little bit of effort, its possible to write much nicer (top-level) code. In this case its about talking to Docker, but the same message holds for many interfaces. First think on how you would express a problem (or rather a solution) in an ideal world, then build interfaces that make it a reality.</p><p>If you’d like to use this code to talk to Docker, just <a href="https://github.com/jhidding/easy-docker.py">fork the github repo</a> and add your own functionality; it’s licensed under Apache v2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3993cb12e906" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/easier-docker-in-python-3993cb12e906">Easier Docker in Python</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>