<?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 Felipe on Medium]]></title>
        <description><![CDATA[Stories by Felipe on Medium]]></description>
        <link>https://medium.com/@f.zapata?source=rss-450c2d7069ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f7WZ93VZ5pv2qgIxOhxJUA.jpeg</url>
            <title>Stories by Felipe on Medium</title>
            <link>https://medium.com/@f.zapata?source=rss-450c2d7069ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:22:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@f.zapata/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[Using Rust for Scientific Numerical applications: Learning from Past Experiences]]></title>
            <link>https://medium.com/escience-center/using-rust-for-scientific-numerical-applications-learning-from-past-experiences-798665d9f9f0?source=rss-450c2d7069ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/798665d9f9f0</guid>
            <category><![CDATA[scientific-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Felipe]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 18:22:17 GMT</pubDate>
            <atom:updated>2021-04-14T12:36:02.349Z</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*ijMaliTc1TsD40XB7YW5GQ.png" /><figcaption>Image: courtesy of <a href="https://www.instagram.com/qiadraws/">Chiara Caratelli</a></figcaption></figure><p>I am a software developer at the <a href="https://www.esciencecenter.nl/">Netherlands eScience Center</a>, where we empower all researchers across all scientific disciplines in the Netherlands by providing the right digital tools for their research. Picture this, a scientist comes to us with a brilliant idea about creating a novel material for improving solar cells or a revolutionary algorithm to grasp the science of protein interactions, but she needs to come out with the high performance software to run hundreds of simulations. Therefore, we work together with them to develop the software tools that can bring their ideas to concrete results.</p><p>Some of these projects involve a lot of number crunching and therefore we need tools to produce lightning-fast applications: enter <a href="https://www.rust-lang.org/">Rust</a>. <a href="https://www.rust-lang.org/">Rust</a> is a low-level language with a welcoming community that <a href="https://www.nature.com/articles/d41586-020-03382-2">stands as a strong competitor to traditional languages like C/C++/Fortran</a> for numerical applications thanks to its performance, memory management system, high abstraction level, and flourishing ecosystem. Check <a href="https://doc.rust-lang.org/stable/book/">the Rust book</a> to get a feeling of the language!</p><blockquote>What I love about Rust is that it has been developed to solve concrete problems, built on top of the lessons (painfully) learnt while implementing real systems.</blockquote><p>At the <a href="https://www.esciencecenter.nl/">Netherlands eScience Center</a>, my main focus is on <a href="https://en.wikipedia.org/wiki/Computational_chemistry">computational chemistry</a> and <a href="https://en.wikipedia.org/wiki/Materials_science">materials science</a>. In these fields, the principles of quantum mechanics are used to generate models that allow the computation of interesting physical and chemical properties. These computations boil down to a lot of <a href="https://en.wikipedia.org/wiki/Linear_algebra"><strong><em>Linear Algebra</em></strong>.</a> In case this sounds like an esoteric math concept to you, let me tell you that linear algebra is the mathematical bedrock upon which all modern machine learning applications are based.</p><p>The beauty of linear algebra is that many scientific and engineering problems can be modeled using numerical operations on vectors and matrices. Among the powerful tools in the linear algebra toolkit, the algorithms to find <a href="https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors">eigenvalues and eigenvectors</a> of a given matrix are the cornerstones for generating quantitative solutions to diverse questions like: “how much energy does a molecule absorb?” or “how much force can be applied on a bridge?” Since the start of computational physics, the scientific community has produced a plethora of libraries and tools to solve those numerical problems, mainly written in C/C++/Fortran.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OdXNA_YpyI6tlQn6" /><figcaption>Photo by <a href="https://unsplash.com/@vlisidis?utm_source=medium&amp;utm_medium=referral">Terry Vlisidis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now the question is: how does Rust compare to the traditional approaches for building number-crunching applications? In this post, I am not going to present benchmarks comparing performance (check <a href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/rust.html">this benchmark</a> if you are curious about how Rust compares to C/C++). Instead, I will focus on what I consider the most important aspects of developing scientific software: <strong><em>development speed and maintainability</em></strong>.</p><p>Do not take me wrong, performance is a top priority. However, if we build a weather model that predicts if we are going to be underwater in a couple of weeks (I live in the Netherlands), making sure that the model is well tested and ruling out the possibility that a <a href="https://en.wikipedia.org/wiki/Segmentation_fault">segmentation fault</a> is going to pop up (after a couple of weeks of simulation), it is then more important than squeezing out the last bit of performance. Therefore, I am going to address the following questions:</p><ul><li>How much effort is needed to build and deploy the software?</li><li>How do I manage the dependencies?</li><li>Can we develop a minimum viable product (MVP) in a reasonable time?</li><li>How much effort is required to test, document, and maintain the code?</li><li>How do I parallelize the application?</li></ul><h3>Implementing an Eigenvalue solver</h3><p>I will address the aforementioned questions using the experience that I gained while creating a Rust package (a.k.a <a href="https://learning-rust.github.io/docs/d4.crates.html">crate</a>) called “e<a href="https://github.com/felipeZ/eigenvalues">igenvalues</a><strong>” </strong>where I have implemented a couple of algorithms to compute the eigenvalues and eigenvectors of a given matrix.</p><p><a href="https://github.com/felipeZ/eigenvalues"><strong><em>Here</em></strong></a> is the link to my eigenvalues library. You can also have a look at the <a href="https://docs.rs/eigenvalues/0.4.0/eigenvalues/"><strong><em>documentation</em></strong></a>.</p><p>The following code snippet shows how to use the e<a href="https://github.com/felipeZ/eigenvalues">igenvalues</a> library,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/868277c11cb6996d2fe4fd978cf10929/href">https://medium.com/media/868277c11cb6996d2fe4fd978cf10929/href</a></iframe><p><strong>How much effort is needed to build and deploy the software?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tji-dAXf4iNkxkAM" /><figcaption>Photo by <a href="https://unsplash.com/@csbphotography?utm_source=medium&amp;utm_medium=referral">Conor Samuel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Number-crunching software usually relies on highly optimized math libraries (e.g. <a href="https://www.openblas.net/">OpenBlas</a>, <a href="http://www.netlib.org/lapack/">Lapack</a>, <a href="https://eigen.tuxfamily.org/">Eigen</a>, <em>etc.</em>)<em> </em>offering low level operations which are used as building blocks to develop more complex calculations. Those dependencies are usually installed by the system administrator or using a Linux package manager (<em>e.g.</em> <a href="https://en.wikipedia.org/wiki/APT_(software)">apt</a>). These dependencies, together with other miscellaneous libraries to parse, log, <em>etc., </em>are then tied together using something like <a href="https://cmake.org/">CMake</a>, which gracefully compiles and links your dependencies. Go ahead, start laughing!</p><p>The previous approach works great on paper, but in reality, developers spend considerable time learning and writing <a href="https://cmake.org/">CMake</a> configuration files (<a href="https://cmake.org/">CMake</a> may not be a programming language by itself but it gets the category of a dialect with its own peculiarities). In addition, looking for the right compiler version and installing the correct dependencies without messing up the other libraries make things so complicated that people literally prefer to write and maintain their own set of tools instead of having to deal with the dependency hell. So, you end up juggling different compiler vendors with their corresponding version, <a href="https://cmake.org/">CMake</a>, your core dependencies, the miscellaneous libraries that you have implemented yourself, and (of course) your code. Finally, the cherry on top: you share the software with your collaborators and they will need to install it in their own environment and deal with their own dependency hell, which will probably be different from yours!</p><p>How does Rust (partially) solve this mess?</p><ul><li>Say goodbye to CMake! You (or your system admin) still need to install the core highly optimized math libraries, but the Rust package manager (a.k.a <a href="https://doc.rust-lang.org/cargo/">Cargo</a>) will solve, install and compile all the dependencies for you.</li><li><a href="https://crates.io/">The Rust community offers mature packages</a> providing the common functionality that you need to write numerical applications.</li></ul><p>Check my <a href="https://github.com/felipeZ/eigenvalues/blob/master/Cargo.toml">dependencies file</a> to get an idea of what kind of information <a href="https://doc.rust-lang.org/cargo/">Cargo</a> (Rust package manager) needs to build your application. In this case, I am using the excellent <a href="https://nalgebra.org/">nalgebra library</a> to build some algorithms on top of nalgebra’s arrays manipulation API.</p><p><strong>Can we develop a minimum viable product (MVP) in a reasonable time?</strong></p><p>In scientific applications, we often start with a model or a hypothesis in mind and we then build software to prove it (or disprove it) and to connect theory to experiments. Given the high levels of uncertainty, we cannot be sure that what we are developing is going to work out, we need to explore a prototype or minimum viable product to corroborate that our ideas are correct, before investing valuable human resources in a project.</p><p>Therefore, it is common to write an MVP in a language like Python that allows to quickly implement an algorithm or method, at the expense of runtime performance (Python is <em>painfully slow, </em>but great for prototyping!). It is extremely risky to develop an MVP in C or Fortran given the complexity and low abstraction level of those languages, meaning that to implement the same concepts we need to write many more lines of code compared to Python.</p><p>But what if we could implement something almost as quickly as in Python but with the C++ speed? Rust again to the rescue!</p><p>Every experienced programmer knows that both their productivity depends on the abstraction level of the language. <em>The fewer lines of code you write, the fewer bugs you introduce.</em> However, an increase in abstraction often results in a higher runtime cost (code that needs to run extremely fast is often <em>very</em> ugly). Rust <a href="https://carette.xyz/posts/zero_cost_abstraction/">zero-cost abstraction</a> allows you to write more concise code by using a higher level abstraction without additional computing cost at runtime. <em>Rust </em><a href="https://doc.rust-lang.org/book/ch13-02-iterators.html"><em>iterators</em></a> are a great example of the power of Rust zero cost abstraction. <em>It is fair to mention that zero-cost abstraction is also central in C++.</em></p><p><strong>How much effort is required to maintain the code?</strong></p><p>If you have ever worked in a medium to large size C/Fortran code base, you certainly know how incredibly difficult and frustrating it can be to maintain it. A recurrent complaint among the programmers in these languages is the dreadful bugs related to unsafe memory management that can take days to trace and reproduce. Fortran programmers are famously known for having <a href="https://nalgebra.org/">segmentation faults</a> for breakfast.</p><p>The Rust type system stands out for its capabilities to rule out memory errors at runtime. The Rust <a href="https://blog.logrocket.com/introducing-the-rust-borrow-checker/">borrow checker</a> is the killer feature that helps to eliminate all those memory bugs while still offering lightning-fast speed.</p><p>Also, as mentioned previously, Rust’s zero cost abstraction allows you to keep a lean code base that is easier to maintain.</p><p><strong><em>Note for C++ developer: </em></strong><em>smart pointers partly alleviate the memory management issues, but the borrow checker can help you to extend the safety guarantees to multithreading code.</em></p><p><strong>How much effort is required to test the code and write documentation?</strong></p><p>Writing documentation in C/C++/Fortran involved bringing a third-party tool like <a href="https://www.doxygen.nl/index.html">Doxygen</a> that we need to install and add to our CMake zoo. Also, we need to learn this tool’s special syntax to write documentation and then pray that the documentation builds.</p><p>Software documentation is essential for scientific code due to the volatile nature of scientific research. <em>Scientific software without documentation is not legacy code but dead code. </em>Given the high barrier imposed by traditional languages to write documentation, it is expected that most scientific software is stillborn due to the impossibility to understand what has been done, even by experts in the same field (or sometimes even by the person who wrote it).</p><p>Documenting a Rust project only requires that you write the documentation in markdown inside the source code as shown in <a href="https://github.com/felipeZ/eigenvalues/blob/master/src/lib.rs">this example</a>. Then you just need to run the cargo doc command and that is it!</p><p>Testing in C/C++/Fortran has a similar fate, they required third-party frameworks that need to be installed and added to CMake. Fortran is particularly painful for testing due to the lack of a standard testing framework, forcing programmers to maintain a bunch of scripts to call the binaries, parse the output, and check the results.</p><p>Rust has a built-in system to test your code, with no third-party libraries. You can have <a href="https://doc.rust-lang.org/nightly/rust-by-example/testing/unit_testing.html">unit tests</a> to check the functionality of a given module at a time, but also <a href="https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html">integration tests</a> to check the public interface of your code. You can even run and test the <a href="https://doc.rust-lang.org/rustdoc/documentation-tests.html">examples in the documentation</a>! In summary, writing and running tests is as effortless as you can get it.</p><p>Lowering the barrier to write tests and documentation is an undervalued feature of Rust. I bet that we all agree that code without tests and documentation is short of useless.</p><p><strong>How do I parallelize the application?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-t4AGVSzZu2_7-jEDMDDg.png" /><figcaption>Image: courtesy of <a href="https://www.instagram.com/qiadraws/">Chiara Caratelli</a></figcaption></figure><p><strong><em>Disclaimer</em></strong><em>:</em> <em>due to my ignorance of the latest Rust developments on multi-node computing (</em><a href="https://en.wikipedia.org/wiki/Message_Passing_Interface"><em>MPI</em></a><em>) and GPU integration, I am going to blatantly ignore those two subjects.</em></p><p>Scientific simulations like weather prediction, protein binding, fluid dynamics, etc<em>.</em> are computationally intensive but often parallelizable (at least on paper!). It goes without saying that we want to make use of all cores available in a given machine. The standard approach is to use something like <a href="https://www.openmp.org/">OpenMP</a> that consists of runtime libraries, compiler directives, <em>etc</em>. to support shared-memory multithreading programming.</p><p>A quite dreaded moment for scientific software developers is when the serial implementation is working and a new parallel version must be implemented. Seriously, parallel implementation in C/C+/Fortran means that all your <a href="https://en.wikipedia.org/wiki/There_are_known_knowns">unknown unknowns</a> about unsafe memory management suddenly uncover all the obnoxious bugs that you didn’t know about until now, and that you need to track for endless hours.</p><p>As a remedy for all that frustration and wasted time, Rust offers a novel approach coined as <a href="https://doc.rust-lang.org/book/ch16-00-concurrency.html">fearless concurrency</a>. This concept refers to the possibility of writing parallel applications that are free of subtle bugs and can be refactored without introducing new bugs.</p><p>But how does Rust achieve this marvelous formula? It turns out that the Rust type system and <a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html">ownership system</a> keep track of what is safe to share across threads, refusing to compile illegal concurrent memory transactions that would have resulted in runtime issues. So, the Rust compiler happily raises compilation errors whenever you are trying to use memory in an unsafe way instead of unleashing Godzilla in the middle of your simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b8oMr9zo7DUTZ_wB" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since Rust is a system programming language, rather than choosing a single parallelism model, it allows multiple low level models like message-passing, share-state, <em>etc</em>. The good news is that we don’t need to use the primitives ourselves, instead, we can use the community-provided libraries like <a href="https://github.com/rayon-rs/rayon">Rayon</a> that build on top of those primitives. <a href="https://github.com/rayon-rs/rayon">Rayon</a> offers powerful functionality like <a href="https://docs.rs/rayon/1.5.0/rayon/iter/index.html">parallel iterators</a> that allow us to execute operations on the elements of an <a href="https://doc.rust-lang.org/book/ch13-02-iterators.html">iterator</a> in parallel, with minimal changes in the source code.</p><p>What is even better, you can use libraries like <a href="https://github.com/rust-ndarray/ndarray">ndarray</a> that has a Numpy-style API to manipulate arrays, while simultaneously offering features like an interface to <a href="https://github.com/rayon-rs/rayon">Rayon</a> to run your array operations in parallel.</p><h3>The Challenges of using Rust for scientific applications</h3><p>Rust is a promising language for scientific applications but there are several challenges that need to be overcome before the language can gain significant traction by the scientific community.</p><ul><li><strong>Rust is a low-level language with many powerful features</strong>. In other words, actually you do not learn Rust during a Saturday afternoon while drinking mojitos. It takes significant effort and time before you can start writing with confidence. Fortunately the Rust community is very open and welcoming and there are always people willing to help. Besides, the compiler has the most informative error messages that I have seen in any programming language. In short, the learning curve is steeper than Python, but you will have a single memory-safe language to rule them all.</li><li><strong>There may be some functionality that is still missing or unstable</strong>. The Rust ecosystem is growing rapidly and more people are coming out with great libraries. The community is always happy to help you to come up with a solution for your missing functionality.</li><li><strong>Interoperability with C/C++</strong>. We certainly do not want to rewrite everything from scratch, therefore we would like to reuse as much code as we can from C/C++. For the Rust community, smooth interoperability with C/C++ is a top priority.</li></ul><h3>Any further thoughts?</h3><p>I hope that I could give you an idea about using Rust for scientific software applications. Comments and thoughts are appreciated.</p><h3>Acknowledgement</h3><p>Thanks to Chiara Caratelli from providing the great drawings. Also my special thanks to <a href="https://medium.com/u/9ef433f5ceb3">Florian Huber</a>, <a href="https://medium.com/u/db1f9f0caae1">Carlos Martinez-Ortiz,</a> <a href="https://medium.com/u/1382ec3ac71f">Patrick Bos</a> and Tom Bakker for their help editing the text.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=798665d9f9f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/using-rust-for-scientific-numerical-applications-learning-from-past-experiences-798665d9f9f0">Using Rust for Scientific Numerical applications: Learning from Past Experiences</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[A Quick and Dirty Pytest Cookbook]]></title>
            <link>https://medium.com/escience-center/a-quick-and-dirty-pytest-cookbook-58051a2980c3?source=rss-450c2d7069ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/58051a2980c3</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Felipe]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 14:25:55 GMT</pubDate>
            <atom:updated>2021-02-22T09:33:23.436Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p><a href="https://docs.pytest.org/en/stable/">Pytest</a> has become the standard tool to test python code. In this post I will show you several tricks and hacks to create, configure and run your tests. without further ado, let’s eat the bugs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0EmQizVVc4_BG8gYWl1sw.jpeg" /><figcaption>Image by Chiara Caratelli</figcaption></figure><h3>Configuring Pytest</h3><p>Since I don’t want to burden my users with testing dependencies, I usually put all the test and documentation dependencies in the <a href="https://extras-require.readthedocs.io/en/latest/">extra_require</a> section of th<em>e </em><strong><em>setup.py</em></strong> file, like:</p><pre>extras_require={<br> &quot;test&quot;: [&quot;coverage&quot;, &quot;mypy&quot;, &quot;pycodestyle&quot;, &quot;pytest&quot;, &quot;pytest-cov&quot;,<br> &quot;pytest-mock&quot;, &quot;pytest-asyncio&quot;]}</pre><p>In this way, when I am developing code, I can install these testing dependencies like:</p><pre>pip install -e .[test]</pre><p>I also like to configure Pytest to automatically look for the tests folder and generate a coverage report. For doing so, I add the following lines in the <a href="https://docs.python.org/3/distutils/configfile.html">configuration <em>setup.cfg</em></a> file:</p><pre>[tool:pytest]<br>testpaths = tests<br>addopts = --cov --cov-report xml --cov-report term --cov-report html</pre><h3>Running the tests in GitHub actions</h3><p>I use<a href="https://docs.github.com/en/actions/quickstart"> GitHub actions</a> to tests my Python code. The following snippet defines the commands that I use to install and run the Pytest dependencies:</p><pre>- name: Install the library<br>        run: |<br>          pip install -e .[test]</pre><pre>- name: Test<br>        run: |<br>          pytest --cov-config setup.cfg</pre><pre>- name: coverage<br>        uses: codecov/codecov-action@v1<br>        with:<br>          file: ./coverage.xml<br>          name: codecov-umbrella</pre><p>The final action takes the automatically generated coverage and send it to <a href="https://github.com/codecov/codecov-action">codecov</a>. Pretty neat, right?</p><h3>Using a temporary folder</h3><p>Sometimes you find yourself wanting to get a temporal folder to write output files from your server, simulation, etc. in order to check that things are going as expected. The following snippet shows you how to do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a20fb40f74e1dfb9e6032032f572d8c2/href">https://medium.com/media/a20fb40f74e1dfb9e6032032f572d8c2/href</a></iframe><p>Notice that tmp_path is an argument provided automatically by Pytest. You just need to use it in your code.</p><h3>Mocking code</h3><p><a href="https://mock.readthedocs.io/en/latest/">Mocking functionality</a> is a cool trick when you need to test expensive or complex code, like calling a web service.</p><p>Let’s suppose that I have a command line interface to interact with a web service and I will like to test its behavior. I would first mock the reading of the user’s arguments by <a href="https://docs.python.org/3/library/argparse.html">argparse</a>, then I would mock the expensive or complex functionality, like calling a web service. The following snippet shows how you can do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df64ef0b1c49d6fb388405b239cf092e/href">https://medium.com/media/df64ef0b1c49d6fb388405b239cf092e/href</a></iframe><p>Notice that the mocker argument is automatically injected by Pytest. For more information check the <a href="https://pypi.org/project/pytest-mock/">pytest-mock page</a>.</p><h3>You can use multiple Pytest fixtures</h3><p>A common pattern when testing is to mock part of the functionality, while writing some output to a file. For doing so, you use both a <em>mocker</em> object and a <em>temporal file</em>, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d8ba3ac404276cdd885cb7bba576c8f/href">https://medium.com/media/8d8ba3ac404276cdd885cb7bba576c8f/href</a></iframe><h3>Checking exceptions</h3><p>Testing that an exception is raised helps to check that your code functionality behaves as expected, for example when the wrong arguments are passed or the user runs into a corner case. The following snippet allows you to test that behavior:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8092baf43a5cc6b46b876849348704b1/href">https://medium.com/media/8092baf43a5cc6b46b876849348704b1/href</a></iframe><h3>Skipping tests</h3><p>Sometimes is very useful to skip a test if a dependency is not present at runtime. Maybe the dependency takes a lot of time to install in the CI or it is a proprietary package that you cannot install easily. You can skip those tests with the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef406c7d48a2a756e4f53443320591f1/href">https://medium.com/media/ef406c7d48a2a756e4f53443320591f1/href</a></iframe><h3>Running MyPy</h3><p>I personally love to use <a href="https://docs.python.org/3/library/typing.html">type hints</a> in my functions and methods. I use <a href="http://mypy-lang.org/">mypy</a> to check that those types make sense. the following snippet presents the configuration that I use to call <a href="http://mypy-lang.org/">mypy</a> on a package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8f41161ba31e0bb1a89bd1ba7fda4d6/href">https://medium.com/media/b8f41161ba31e0bb1a89bd1ba7fda4d6/href</a></iframe><p>Notice that you need to define a <a href="https://mypy.readthedocs.io/en/stable/config_file.html">mypy.ini</a> file somewhere in your repository ( I put that file inside the <em>tests</em> folder). I also prefer that the mypy raises some warnings if there are issues with the types instead of raising a (very annoying) error.</p><p>As an alternative to the above snippet, you can install and run the <a href="https://pypi.org/project/pytest-mypy-plugins/">pytest-mypy-plugins</a>.</p><h3>Testing the documentation</h3><p>Testing the documentation is a must have. The following snippet shows how you can do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25e6688a010946adf64bfbe0abcef596/href">https://medium.com/media/25e6688a010946adf64bfbe0abcef596/href</a></iframe><h3>Testing async code</h3><p>If you do web applications or something similar you probably have run into Python <a href="https://docs.python.org/3/library/asyncio.html">asyncio</a>. If you try to run async code using normal pytest code, chances are that you wouldn’t notice that there are no tests running at all. <em>Async code is lazy and requires that you run it inside an async block</em>, otherwise nothing interesting happens. The following snippet shows how to invoke async code in Pytest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b400830b72cb267b163f39ac0c005d6e/href">https://medium.com/media/b400830b72cb267b163f39ac0c005d6e/href</a></iframe><p>For more details about testing asynchronous code in python check <a href="https://github.com/pytest-dev/pytest-asyncio">pytest-asyncio</a>.</p><h3>Running tests in parallel</h3><p>If you, like me, have the tendency to procrastinate while waiting for the test suite to finish executing, then a good way to reduce the procrastination time is to run the tests in parallel.</p><p>For running your tests in parallel, you just need to install the <a href="https://github.com/browsertron/pytest-parallel">pytest-parallel</a> library that not only allows you to run your tests in parallel but also in a thread-safe manner, using commands as simple as:</p><pre>pytest --workers 2</pre><h3>Running a test with multiple parameters</h3><p>Imaging that you have a simulation that receives some parameters as input and gives you back some numerical output. You can use <a href="https://docs.pytest.org/en/stable/parametrize.html">pytest’s parametrize extension</a> to feed one parameter at a time to the simulation and check that each one of them returns the expected output. The following snippet shows how to accomplish that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41af5a2591c79b771d7deaee0a898d53/href">https://medium.com/media/41af5a2591c79b771d7deaee0a898d53/href</a></iframe><p>If you run the previous snippet, you should see something like:</p><pre>pytest -v test_parameters.py<br>test_parameters.py::test_simulation[pi-3.141592653589793] PASSED                                      <br>test_parameters.py::test_simulation[exp-2.718281828459045] FAILED</pre><pre>parameter = &#39;exp&#39;, expected = 2.718281828459045</pre><pre><a href="http://twitter.com/pytest">@pytest</a>.mark.parametrize(&quot;parameter, expected&quot;, <br>                         [(&quot;pi&quot;, np.pi), (&quot;exp&quot;, np.exp(1))])<br>    def test_simulation(parameter: str, expected: float) -&gt; None:<br>        &quot;&quot;&quot;Check the simulation.&quot;&quot;&quot;<br>        result = run_simulation(parameter)<br>&gt;       assert abs(result - expected) &lt; 1e-8<br>E       assert 39.28171817154095 &lt; 1e-08<br>E        +  where 39.28171817154095 = abs((42 - 2.718281828459045))</pre><pre>test_parameter.py:16: AssertionError</pre><h3>Conclusions</h3><p>Pytest is a flexible tool with a great number of useful extensions. With Pytest, there is always a way to check your code functionality, even those annoying corner cases.</p><p>Please comment if you find these tricks useful or if you find another nice trick that you want to share.</p><h3>Acknowledgement</h3><p>My special gratitude to Bas van Beek to share with me some of his useful recipes. I would like also to thank <a href="https://medium.com/u/9ef433f5ceb3">Florian Huber</a> and Stefan Verhoeven for their feedback.</p><p>Thanks to <a href="https://medium.com/u/24f09ca64482">Pablo Rodríguez-Sánchez</a> and Steven Roldan for their help editing the text.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58051a2980c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/a-quick-and-dirty-pytest-cookbook-58051a2980c3">A Quick and Dirty Pytest Cookbook</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[Building a Web Service to Manage Scientific Simulation Data Using GraphQL]]></title>
            <link>https://medium.com/escience-center/building-a-web-service-to-manage-scientific-simulation-data-using-graphql-a0bbf1c3f6e9?source=rss-450c2d7069ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0bbf1c3f6e9</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Felipe]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 08:55:56 GMT</pubDate>
            <atom:updated>2021-01-15T13:58:05.134Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Scientific simulations generate large volume of data that needs to be stored and processed by multidisciplinary teams across different geographical locations. Distributing computational expensive simulations among the available resources, avoiding duplication and keeping the data safe are challenges that scientists face every day.</p><p>In this post we present our web service <a href="https://github.com/nlesc-nano/ceiba">Ceiba</a> and its command line interface <a href="https://github.com/nlesc-nano/ceiba-cli">Ceiba-cli</a>. Ceiba solves the problem of <em>computing</em>, <em>storing</em> and <em>securely sharing</em> computationally <em>expensive</em> simulation results. Researchers can save significant time and resources by easily computing new data and reusing existing simulation data to answer their questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bI9DbwobcmYvOYyk" /><figcaption>Photo by <a href="https://unsplash.com/@publicpowerorg?utm_source=medium&amp;utm_medium=referral">American Public Power Association</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Scientific simulations and data</h3><blockquote>At the <a href="https://www.esciencecenter.nl/">Netherlands eScience Center</a> we empower academic researchers by building together simulation tools, data pipelines, etc. A common goal among several tools that we develop for projects in different scientific fields, is to reduce the calculation time of computationally expensive physical simulations (e.g. molecular processes) by applying statistical methods to previously simulated data.</blockquote><p>The aforementioned methodology can potentially save us significant human and computational resources by easily generating high value data using previous computations. But before we are ready to apply any statistical method we of course need the data and for doing so, we need to ask ourselves questions like:</p><blockquote>What input is required?</blockquote><blockquote>Who is going to perform the simulation?</blockquote><blockquote>What facilities are going to be used?</blockquote><blockquote>Where is the resulting data going to be stored?</blockquote><blockquote>How to access the available data?</blockquote><p>Physical simulations usually require intricate input that takes into consideration several aspects and parameters used by different models to approximate the phenomena under consideration. Also, scientific simulations are computationally demanding tasks, so they are usually run in (inter)national supercomputers or very specialized facilities. We also want to maximize the impact of the data in the scientific community, therefore we want other scientists to be able to access the data and even add their own, but we need some security layers to protect such valuable data.</p><p>There is no silver bullet to address all the previous questions, but there are amazing initiatives like the <a href="https://foldingathome.org/">folding at home project</a> that distributes some computational tasks among volunteers around the world who give away some time in their computers to simulate protein dynamics.</p><p>It seems that if we want to collaborate on the distribution of computational tasks and the assemblage of the resulting data, we need a central “entity” that (1) allows users to request new tasks, (2) receives the task’s results to be stored and (3) returns some available data when requested. It sounds like we need a web service!</p><blockquote>Writing a web service is a nontrivial task, you need to be aware of different technologies, libraries, etc. while making sure that your data is going to be safe and of course you need some infrastructure to host your service. This post goal is to give you some hints about building a web service for scientific applications and it is by no means a complete guide to writing web applications.</blockquote><h3>A pull/push model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HnAn4y-BQGmvGjGZ" /><figcaption>Photo by <a href="https://unsplash.com/@johnschno?utm_source=medium&amp;utm_medium=referral">John Schnobrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before entering into the web service technical details, let’s explore what its behavior should be.</p><p>So, once it has been decided what are the best approximations and models to perform the simulations, we can compile all the simulation metadata into different jobs. For instance, a job can be a single molecular simulation under some specific conditions. We would like to make all these jobs available to the users, in such a way that they can run one or more jobs at a time but avoiding that the same job is run by more than one user.</p><p>It would be great that when the simulation is done a user can send the results to the web service or ask for already available results. We also want to be able to call the web service from our local computer, specialized infrastructure or wherever we want to perform the computation, without worrying about where the service is running.</p><p>It seems, that we want a <a href="https://en.wikipedia.org/wiki/Git">Git</a>-like behavior where we can pull jobs (or available data) and push results.</p><p>With these requirements in mind, I have developed an open source web service called <a href="https://github.com/nlesc-nano/ceiba">Ceiba</a>. Let’s see how it works!</p><h3>The client</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P4hHvh84YZQLPGgi" /><figcaption>Photo by <a href="https://unsplash.com/@andrew_gook?utm_source=medium&amp;utm_medium=referral">Andrew Gook</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The web service consists of two parts: a small command line interface (CLI) that communicates with the service and the <a href="https://github.com/nlesc-nano/ceiba">Ceiba web service</a> that handles all the data.</p><p>Our CLI is called <a href="https://github.com/nlesc-nano/ceiba-cli">Ceiba-cli</a> and it offers several actions to interact with the service, like logging in, computing, querying, etc. as shown in the following snippet:</p><pre>&gt;&gt;&gt; ceiba --help<br>usage: ceiba [-h] [--version] {login,compute,report,query,add,manage} ...</pre><pre>positional arguments:<br>  {login,compute,report,query,add,manage}<br>                        Interact with the properties web service<br>    login               Log in to the Ceibaweb service<br>    compute             Compute available jobs<br>    report              Report the results back to the server<br>    query               Query some properties from the database<br>    add                 Add new jobs to the database<br>    manage              Change jobs status</pre><pre>optional arguments:<br>  -h, --help            show this help message and exit<br>  --version             show program&#39;s version number and exit</pre><p>Using <a href="https://github.com/nlesc-nano/ceiba-cli">Ceiba-cli</a> we can compute some jobs using a command like:</p><pre>ceiba compute -c collection_name -j number_of_jobs_to_compute</pre><p>The previous command handles the communication with the web service, fetches the requested jobs from a given collection (or dataset) and runs them directly or invokes a <a href="https://en.wikipedia.org/wiki/Job_scheduler">job scheduler</a> like <a href="https://slurm.schedmd.com/documentation.html">Slurm</a>. To communicate with the service, <a href="https://github.com/nlesc-nano/ceiba-cli">Ceiba-cli</a> invokes the <a href="https://requests.readthedocs.io/en/master/">Python Requests library</a> that handles the communication.</p><p>Once the jobs are done we can report the computed data like:</p><pre>moka report</pre><p>You may be wondering how does the client know what data it needs to send/receive. Well, that is the subject of the next section!</p><h3>The Ceiba web service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o_Zzwgbaexr6Fz8y" /><figcaption>Photo by <a href="https://unsplash.com/@tofi?utm_source=medium&amp;utm_medium=referral">Tobias Fischer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The main goal of the web service is to minimize the interaction between the users and the data. If the client requests some read-only action you just return the data (if available) and if the client wants to change something, you need to ensure that (1) the client has permissions to mutate the data (2) only the mutations specified by the client are carried out but nothing more. I will skip authentication in this post.</p><p>Therefore, the <a href="https://github.com/nlesc-nano/ceiba">Ceiba</a> web service needs to handle two kinds of requests by the client: read-only queries and mutations on the datasets. These “queries” and “mutations” can be easily describe with <a href="https://graphql.org/">GraphQL</a>.</p><p>In a nutshell, <a href="https://graphql.org/">GraphQL</a> defines a contract (known as a schema) between the actions that a client can perform with the web service and the possible outcomes of those actions. More formally, <a href="https://graphql.org/">GraphQL</a> is a query language that allows you to specify an application Programming interface (API) using different programming languages. If you have previous experience with <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">RESTful API</a> have a look at a comparison between <a href="https://www.howtographql.com/basics/1-graphql-is-the-better-rest/">GraphQL and REST</a>.</p><p>But how does GraphQL work? First, you need to define a schema using the <a href="https://graphql.org/">GraphQL</a> schema language. The following code snippet defines a schema to query a job using its status,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab2ef6eb1e1d79fe340c190f058070fe/href">https://medium.com/media/ab2ef6eb1e1d79fe340c190f058070fe/href</a></iframe><p>The <strong>Query</strong> schema specifies that in order to request some <strong><em>jobs</em></strong> you need to provide a <em>Status</em> argument, where <em>Status</em> can be one of four possibilities: <em>AVAILABLE, DONE, FAILED</em> and <em>RUNNING. </em>The exclamation mark (!) indicates that the argument cannot be <em>Null</em> (a.k.a <em>None</em> in Python).</p><p>The following <strong>Mutation</strong> schema defines the required arguments to update a given job status.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e04d4b0b1aeb3aa8099c124846d1e02/href">https://medium.com/media/4e04d4b0b1aeb3aa8099c124846d1e02/href</a></iframe><p>The <strong><em>updateJob</em></strong> action specifies that you must provide an <em>id</em> and a <em>new_status</em> in order to be able to update a job. You will receive a <em>Reply</em> specifying whether the update action has succeeded.</p><p>Have a look at the Ceiba <a href="https://github.com/nlesc-nano/insilico-server/blob/master/insilicoserver/sdl/Query.graphql">queries</a> and <a href="https://github.com/nlesc-nano/insilico-server/blob/master/insilicoserver/sdl/Mutation.graphql">mutations</a> schemas. They are slightly more complex than the aforementioned schemas but follow the same rationale as the previous examples. You can also have a look at the official <a href="https://graphql.org/learn/">introduction to GraphQL</a>.</p><p>We have just defined the schemas that specify the actions that we want to perform. We still need to implement the actions and for doing so, we need a GraphQL engine: a library that takes the schemas together with the code that implements the actions and generates an API.</p><p>We have chosen the <a href="https://tartiflette.io/">Tartiflette GraphQL engine</a> to implement our web service mostly because it is easy to use and open source. The following snippet shows a possible implementation for querying jobs based on their status using <a href="https://tartiflette.io/">Tartiflette</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b38cc367dec0c61f07698496b6f165/href">https://medium.com/media/a3b38cc367dec0c61f07698496b6f165/href</a></iframe><p>the <strong><em>Resolver</em></strong> decorator indicates that the <strong><em>resolver_query_jobs</em></strong> function corresponds to the implementation of the <strong><em>query jobs</em></strong> schema. The function takes 4 arguments of which I only use <strong><em>args</em></strong> and <strong><em>ctx</em></strong><em> </em>(You can refer to <a href="https://tartiflette.io/">Tartiflette</a> for further details). <strong><em>args </em></strong>contains the arguments given by the client code, while <strong><em>ctx </em></strong>contains the context for running the current function, for example the handler to access the database that is called <strong><em>mongodb</em></strong> in this code snippet.</p><p>Notice that the definition of the aforementioned function starts with the <em>async</em> keyword. <a href="https://docs.python.org/3/library/asyncio.html">Asyncio</a> is a popular built-in Python library to write concurrent code. It is extensively used to write high performance web services.</p><p>In the Ceiba web service implementation of the <a href="https://github.com/nlesc-nano/insilico-server/tree/master/provisioning"><strong>queries</strong></a> and <a href="https://github.com/nlesc-nano/insilico-server/blob/master/insilicoserver/mutation_resolvers.py"><strong>mutations</strong></a>, there are definitions for all the Python functions that perform the actions specified in the GraphQL schemas. For each query and mutation, there is a corresponding function.</p><h3>The database</h3><p>We need a database not only for storing the interesting data but also to store the jobs metadata, like what jobs are available. For the Ceiba web service we use <a href="https://www.mongodb.com/">MongoDB</a>.</p><p>My personal opinion is that a <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL database</a> like <a href="https://www.mongodb.com/">MongoDB</a> gives a significant advantage over traditional SQL databases on research projects where up-front design of the schemas to store data is unfeasible. The research priorities can change as the project evolves and having dynamic schemas to store the data makes the researchers’ lives easier.</p><h3>Putting all together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tX3PYMK5Q1yW02qK" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_source=medium&amp;utm_medium=referral">frank mckenna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://www.docker.com/">Docker containers</a> are the perfect way to ship our web service. We just need to write a <a href="https://github.com/nlesc-nano/insilico-server/blob/master/Dockerfile">Dockerfile</a> with the recipe to install and start the service together with the <a href="https://hub.docker.com/_/mongo">mongo container</a>.</p><p>If you want to deploy the Ceiba web service to a remote server you need to follow these steps:</p><ol><li>Install <a href="https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html">Ansible</a> in your computer.</li><li>Clone the <a href="https://github.com/nlesc-nano/ceiba">Ceiba</a> repo and go to the <a href="https://github.com/nlesc-nano/insilico-server/tree/master/provisioning">provisioning</a> folder.</li><li>Edit the <a href="https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html">inventory</a> file with the address of the server(s) where you want to install the runner.</li><li>Edit the <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks.html">playbook</a> file with the remote_user name for the remote servers.</li><li>Make sure that you can ssh to your server(s).</li><li>Install the runner with the following command:</li></ol><pre>ansible-playbook -i inventory playbook.yml</pre><p>The Ceiba server should be up and running!</p><h3>The pesky details</h3><p>You certainly do not want to keep your web service open, so people can remove your data. You want that users are authenticated before using your service, but you also do not want to manage all the security on your own. Getting authentication right using something like <a href="https://en.wikipedia.org/wiki/OAuth">OAuth2</a> is tricky and it needs at least an entire post on its own.</p><p>Also, you need to host your web service somewhere and <strong>hosting costs money</strong>. It is simply not viable that you host your service in your computer, it is not safe and it takes too much time to maintain. Fortunately for researchers, there are institutions like <a href="https://www.surf.nl/en">SURF</a> that can help you to host a web service for research purposes.</p><h3>Acknowledgement</h3><p>Creating the Ceiba web service would not be possible without <a href="https://www.esciencecenter.nl/team/stefan-verhoeven-bsc/">Stefan Verhoeven</a> advice and the computational resources provided by <a href="https://www.surf.nl/en">SURF</a>.</p><p>I will also to thank <a href="https://www.esciencecenter.nl/team/dr-jens-wehner/">Jens Wehner</a>, <a href="https://www.esciencecenter.nl/team/dr-nicolas-renaud-2/">Nicolas Renaud,</a> <a href="https://www.esciencecenter.nl/team/johan-hidding-msc/">Johan Hidding</a>, <a href="https://www.esciencecenter.nl/team/dr-pablo-lopez-tarifa/">Pablo Lopez-Tarifa</a> and <a href="https://www.esciencecenter.nl/team/victor-azizi-msc/">Victor Azizi</a> for their feedback and support.</p><p>Specially thanks to <a href="https://medium.com/u/1382ec3ac71f">Patrick Bos,</a> <a href="https://github.com/nlesc-nano/insilico-server/tree/master/provisioning">Tom Bakker</a> for their feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0bbf1c3f6e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/building-a-web-service-to-manage-scientific-simulation-data-using-graphql-a0bbf1c3f6e9">Building a Web Service to Manage Scientific Simulation Data Using GraphQL</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[Some thoughts about developing software for scientific applications]]></title>
            <link>https://medium.com/escience-center/some-thoughts-about-developing-software-for-scientific-applications-3dceb6209471?source=rss-450c2d7069ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dceb6209471</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Felipe]]></dc:creator>
            <pubDate>Wed, 29 May 2019 08:50:20 GMT</pubDate>
            <atom:updated>2019-06-07T12:01:24.616Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>…The children would remember for the rest of their lives the august solemnity with which their father, devastated by his prolonged vigil and by the wraith of his imagination, revealed his discovery to them:</blockquote><blockquote>-‘The world is round, like an orange.’</blockquote><blockquote>― <strong>Gabriel Garcí­a Márquez, One Hundred Years of Solitude</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*stxtWjVMWisEjKv8" /><figcaption>Photo by <a href="https://unsplash.com/@bendavisual?utm_source=medium&amp;utm_medium=referral">Benjamin Davies</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I have been reading a wonderful book called: <a href="https://en.wikipedia.org/wiki/Thinking,_Fast_and_Slow"><em>Thinking, fast and slow</em></a><em>. </em>In that book, David Kahneman brilliantly guides us through the <a href="https://en.wikipedia.org/wiki/Dual_process_theory">two system model </a>representing the thought process: a fast system in charge of the automatic behavior and a slow one taking analytical decisions. Mr. Kahneman insistently warns us, in his very clever humor, about the lazy slow system and the biased decision-making of the fast system. In this post I will borrow these ideas to share my experience about designing and implementing scientific software.</p><p>Also, in contrast to my <a href="https://blog.esciencecenter.nl/dealing-with-dragons-and-monsters-best-practices-for-handling-legacy-code-35bb9c939b7d">previous blog</a> post in which I briefly introduced some guidelines to deal with legacy code, in this one I would like to embark with you on a new journey to the promised land full of nothingness where we can start (almost) from scratch!</p><h4>The world is round, like an orange!</h4><blockquote>“Our comforting conviction that the world makes sense rests on a secure foundation: our almost unlimited ability to ignore our ignorance.” <br>― Daniel Kahneman</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*82ZMt6M1u2kNP0Lf" /><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><p>Lets start from the beginning: planet earth. One given day on earth, <em>José Arcadio Buendía</em>, one of the main characters of o<a href="https://en.wikipedia.org/wiki/One_Hundred_Years_of_Solitude">ne hundred years of solitude</a>, discovered after many months of effort and pain that the earth is round! Which is great, apart from the fact that the Greeks knew it a couple of millennia before.</p><p>Scientific software developing is full of <em>José</em> Arcadios, they wake up early on the morning and spend febrile days playing with mathematical model in the shape of quick and dirty script that are going to be hopefully clean and polish on the future. Of course, as the famous software engineer <a href="https://blog.cleancoder.com/">Robert Martin</a> brilliantly explains in his <a href="https://www.pearson.com/us/higher-education/program/Martin-Clean-Code-A-Handbook-of-Agile-Software-Craftsmanship/PGM63937.html">clean code book</a>, the code never gets clean and it becomes yet another spaghetti monster.</p><p>So, what can you do to create flexible and functional software for scientific applications? There are many great books about software architecture like <a href="https://learning.oreilly.com/library/view/clean-architecture-a/9780134494272/">clean architecture</a> and<a href="https://www.oreilly.com/library/view/the-pragmatic-programmer/020161622X/"> the pragmatic programmer</a>. However, when developing software for scientific applications, we usually do not have a set of well defined specifications, instead we just have hunches and vague ideas of what may or may not work.</p><p>Since we lack a concrete plan, our mind continuously plays tricks on us, making us to believe that we possess both unlimited time and resources. Professional software architects are quite conscious about this <a href="https://en.wikipedia.org/wiki/Planning_fallacy">planning fallacy</a> and have years of experience and painful mistakes to remind them about those biases. But scientific software is usually the toil of a <a href="https://arxiv.org/abs/1904.09954">single or few heroes</a> who work day and night to create software, crunch data and analyze results.</p><p><strong>The question is then how can we make a concrete plan for implementing half-proven ideas</strong>?</p><p><em>What I have found is that the unknowns of the projects can be treated as black boxes that can be encapsulated in a flexible framework. This framework, allows to replace one black box by another with an small amount of effort.</em></p><p>In this blog I would like to introduce a simple guideline about best practices for designing scientific software, without entering in any religious battles about whether <a href="https://en.wikipedia.org/wiki/Agile_software_development">Agile</a> methodologies like <a href="https://en.wikipedia.org/wiki/Scrum_(software_development)">Scrum</a> are suitable for scientific software development.</p><h4>Make a clear plan and discuss it with others</h4><blockquote>“many people are overconfident, prone to place too much faith in their intuitions.”</blockquote><blockquote>― Daniel Kahneman</blockquote><p>A whiteboard or a piece of paper is a great place to start designing software. Discuss over a cup of coffee with your colleagues what is the functionality that you are expecting from the software. Make a scheme representing the functionality as boxes and the relation between the functions as edges, do not enter on the details of the algorithms for the moment being. Then ask yourself:</p><ul><li>Are the components of you design orthogonal? This means that you can replace one component by another without having to change all the other components.</li><li>Is there some information that is duplicate or can be derived from a higher abstraction level?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vh8bBvgToPFAyBLk" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico?utm_source=medium&amp;utm_medium=referral">Kaleidico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Once you have a draft about the functionality and its dependencies, look up for the parts of the system that are independent from the current unknowns of the project. Those independent parts constitute the backbone of your framework and should be flexible enough to allow to plugin other components.</p><p>The development of a modular and flexible software may seem costly, but the invested time will be amortized on the future when you would need to replace a part of the system without having to restart from scratch. And believe me, that is always going to happen!</p><p>If the previous design rings a bell, have a look at the <a href="https://www.oreilly.com/library/view/software-architecture-patterns/9781491971437/ch03.html">microkernel architecture</a>!</p><h4>Test Driven Development</h4><blockquote>“We are prone to overestimate how much we understand about the world and to underestimate the role of chance in events.”</blockquote><blockquote>―David Kahneman</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G2kcC7G4TFHygK9s" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You may think that since you are navigating uncharted seas, you need to play with the models before testing the code. But, if your goal is to prove an hypothesis based on some data or algorithm, should you not been testing the code that represents the hypothesis since the beginning?</p><p><a href="https://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development</a> is completely ignored or at best frown upon in scientific software development, but the nature of this software development methodology is deeply rooted on the scientific method. You need to first identity the properties that your system should have and then you progressively build your system around a set of tests that check for the expected functionality.</p><h4>Avoid social embarrassment: use the standard libraries</h4><blockquote>“true experts know the limits of their knowledge”</blockquote><blockquote>―David Kahneman</blockquote><p>Duplication and re-implementation of well known algorithms should be avoided, correctness is more important than performance. Remember that the main goals of a scientific library is first reproducibility and then performance. A flexible, well-tested and well-documented library can always be improved in the future.</p><p>As <a href="https://en.wikiquote.org/wiki/Donald_Knuth">Donald Knuth</a> famously said: “Premature optimization is the root of all evil”. You first goal should be a functional and well tested library, once you have something that works as expected, you can start profiling and optimizing.</p><h4>Finally</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wbN9foCe_njdkMbr" /><figcaption>Photo by <a href="https://unsplash.com/@aaronburden?utm_source=medium&amp;utm_medium=referral">Aaron Burden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is no single recipe that covers all the technical problems for a given scientific application, but identifying the software requirements and the known-unknowns will help you to create a crude chart to navigate the sea of monsters and uncertainties on a scientific software development voyage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dceb6209471" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/some-thoughts-about-developing-software-for-scientific-applications-3dceb6209471">Some thoughts about developing software for scientific applications</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[Dealing with Dragons and Monsters: Best Practices for Handling Legacy Code]]></title>
            <link>https://medium.com/escience-center/dealing-with-dragons-and-monsters-best-practices-for-handling-legacy-code-35bb9c939b7d?source=rss-450c2d7069ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/35bb9c939b7d</guid>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[scientific-software]]></category>
            <dc:creator><![CDATA[Felipe]]></dc:creator>
            <pubDate>Wed, 09 Jan 2019 09:25:02 GMT</pubDate>
            <atom:updated>2019-01-09T09:37:14.734Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>“So comes snow after fire, and even dragons have their endings.” <br>― <strong>J.R.R. Tolkien, </strong><a href="https://www.goodreads.com/work/quotes/1540236"><strong>The Hobbit</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frYHQLnu7557WfFq0j7L1w.png" /><figcaption>Typical debugging session</figcaption></figure><p>When I started my PhD in the field of <a href="https://en.wikipedia.org/wiki/Computational_chemistry">computational chemistry</a> I was given the task of improving and contributing to different pieces of code in the infamous <a href="https://en.wikipedia.org/wiki/Fortran#FORTRAN_77">FORTRAN 77 standard</a>. I gathered all my courage and spent several months banging my head against a wall of esoteric compilation errors trying to decipher the arcane arts of compiling and running legacy code.</p><p>Back then the basic idea was to dig into all the blogs, documents and different Q&amp;A sites, then muddle through the code until it compiled. Subsequently, I put warnings for all the unfortunate souls that would have to deal with the spaghetti monster in the future, warning them to not touch this and that keyword under the threat of eternal damnation.</p><blockquote>Then, I wondered: if dealing with legacy code is such a nightmare, why do we not throw away all the legacy code and start from scratch?</blockquote><p>Yes, legacy code is ugly, convoluted and sometimes it is indistinguishable from <a href="https://en.wikipedia.org/wiki/Black_Speech">black speech of Mordor</a> (see for instance: <em>goto</em>, <em>rewind</em> and <em>common blocks</em><strong>). </strong>But, <em>in general scientific legacy code contains the tears, sweat and blood of researchers who have spent many days and nights implementing new features and fixing bugs</em>. You can argue that all the knowledge lies within publications and therefore we can throw everything away and start from scratch, but as discussed in <a href="https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/">this excellent post</a>, the answer is more complex than that and we still need to produce working code while keeping the previous developments alive.</p><blockquote>So, how do we then face legacy code while maintaining our sanity?</blockquote><h3>The quest</h3><p>Before embarking on any enterprise about maintaining/modernizing legacy code, let me tell you that on my experience the war against bad code is won battle by battle, one at a time, so be wise when choosing your battles. Experience will tell you what the most urgent issues are to fix, provided that you have experience on the code that you are working on. But since that is seldom the case, the first step to take is read as much as you can about the language/tool that you are going to use.</p><blockquote>The time that you spend reading material related to your project’s programming languages, libraries, tools, etc. will pay you back many times in the future when you identify an issue and immediately know how to deal with it.</blockquote><p>If you happened to run into a<em> C++</em> legacy monster go and read <a href="http://shop.oreilly.com/product/0636920033707.do"><em>Effective modern C++</em></a><em>. </em>On the other hand if you need to deal with <em>FORTRAN</em>, I would recommend you to have a look at <a href="https://global.oup.com/academic/product/modern-fortran-explained-9780198811893?cc=nl&amp;lang=en&amp;"><em>Modern Fortran Explained</em></a><em>.</em></p><p>Now, if we follow the<a href="https://en.wikipedia.org/wiki/Pareto_principle"> Pareto principle</a>, we can expect that roughly 80% of the performance/functionality of a given software, depends on approximately 20% of the source code. This rule of thumb basically means that we do not need to change every single line of code, but just some core components that most of the functionality depends on. A <a href="https://en.wikipedia.org/wiki/Profiling_(computer_programming)"><em>profiler</em></a> is the tool that will help you to identify the hot spots of your software. Profilers can be used together with <a href="https://github.com/jrfonseca/gprof2dot"><strong><em>gprof2dot</em></strong></a> to generate a graph showing the most used functions together with their dependencies.</p><h3>The strategy</h3><blockquote>Would you go on the quest for unraveling the mysteries of the universe with a rusted and lousy tool?</blockquote><p>Once you know how to use the tools of your language and have identified the core functionality of your software, it is time to reflect on what you want to get out of the code. You may come out with several words like: performance, efficiency, etc. but if you are doing science, in my view the really important word is <strong><em>reproducibility</em></strong><em>. </em>Reproducibility is fundamental within science, because it is what sets up the basis of hypotheses and subsequently theories. Without it we will go blind searching for ghosts.</p><p>To my knowledge, there are three fundamental features that scientific code must contain in order to be reproducible: <strong><em>a test suite, a portable installation </em></strong><em>and</em><strong><em> documentation</em></strong>. A test suite is simply a collection that asserts that a software behaves as expected. While a portable installation refers to a simple procedure that allows to easily install the software in different platforms and operative systems. I will elaborate more about these three important features in the following section.</p><p>Notice that these three features are extremely difficult to implement without a <a href="https://guide.esciencecenter.nl/best_practices/version_control.html">version control system</a>, that in modern scientific development boils down to using <a href="https://git-scm.com/book/en/v2"><strong><em>git</em></strong></a><strong> </strong>(specifically one of the several free <a href="https://medium.com/flow-ci/github-vs-bitbucket-vs-gitlab-vs-coding-7cf2b43888a1"><strong><em>repository management services</em></strong></a>). I am aware that there are some politics among scientists against making the code open source, mainly due to the prejudice that someone else is going to steal their ideas. Admittedly, no serious scientist will go through the pain of understanding thousands of lines of obfuscated code to steal a complex mathematical model that is already public knowledge. But more importantly, science is about probing reality with experiments and simulations. How can an obscure and inaccessible code achieve those goals?</p><h3>Even heroes need help</h3><blockquote>Do not reinvent the wheel, use the high quality and free available software for testing and building</blockquote><h4>Testing</h4><p>A test suite is extremely important since it will guarantee that we do not introduce new bugs when we are refactoring the core components. If there are no tests you may need to come out with your own test suite using a <a href="https://guide.esciencecenter.nl/best_practices/testing.html"><em>test infrastructure for your </em>language</a>. Notice that testing does not mean to run the whole software with hundreds of complicated calculations in a supercomputer, producing Gigabytes of output. Testing is about making sure that small components (e.g. functions and methods) behave as you expect. Yes, it means that you should have a lot of small tests! Also, in order to help with the process of refactoring the legacy code you will certainly need to get familiar with the concept of <a href="https://realpython.com/python-continuous-integration/"><strong>continuous integration</strong></a>.</p><h4>Installation</h4><p>Legacy code usually lacks a portable installation and users are forced to deal with low level shell scripts or <a href="https://www.gnu.org/software/make/">Make files</a> (or whatever <a href="https://en.wikipedia.org/wiki/Build_automation">build system</a> you are using), in order to install the code. If you are using C/C++ or FORTRAN, <a href="https://cmake.org/"><strong>CMake</strong></a> is the tool that you are looking for in order to make your software easy to install, most of the instructions that you will need are nicely explained in the<a href="https://www.packtpub.com/application-development/cmake-cookbook"> CMake Cookbook</a>.</p><blockquote>Being portable is important not only for the people interested in using the software but also for you in order to work in a continuous integration model<em>.</em></blockquote><h4>Documentation</h4><p>Testing and installing the code is half of the story, a software without documentation is basically inaccessible even for the experts in a given field. By documentation I do not mean a lengthy and detailed description of every feature available in the software. What users of the software want to see is a short and clear description of a given feature or functionality, while implementation details can be moved to the source code.</p><p>There are several choices to write documentation in C/C++, while for FORTRAN the standard tool is <a href="https://github.com/doxygen/doxygen"><strong>Doxygen</strong></a>. For an extensive discussion about how to write documentation for scientific code, check the <a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1006561">Ten simple rules for documenting scientific code</a>.</p><h3><strong>“</strong><a href="https://en.wikipedia.org/wiki/Here_be_dragons"><strong>Here be dragons</strong></a><strong>”</strong></h3><p>Together we have just piped out at some guidelines and tools to face scientific legacy code. They are not silver bullets and only intended to give some help when navigating uncharted seas. Finally, bear in mind that cleaning, testing and documenting while coding are the most powerful tools against prospective code-monsters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35bb9c939b7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/dealing-with-dragons-and-monsters-best-practices-for-handling-legacy-code-35bb9c939b7d">Dealing with Dragons and Monsters: Best Practices for Handling Legacy Code</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>