diff --git a/applications/README.md b/applications/README.md index 89ddea7a2a090508bda2950b4ab29efd3b634344..e1cfe31aa0248ee8f1219d977f53e19d71bc70a9 100644 --- a/applications/README.md +++ b/applications/README.md @@ -12,3 +12,4 @@ Practicals are split into the following sub-categories (and sub-folders): 3. `matlab_vs_python` : a number of data analysis examples with head-to-head comparisons between matlab and python code. 4. `modelling` : multiple examples of analysis methods in python. 5. `pandas` : processing and analsing tabular data with the powerful Pandas package. +6. `parallel` : Third-party libraries and strategies for parallelising Python code. diff --git a/applications/parallel/parallel.ipynb b/applications/parallel/parallel.ipynb index acfb2866d366bbd7347c36e42ed4e577e9bce185..83b765aa7a9a66ee26f9243a7423e7ccad69e3d0 100644 --- a/applications/parallel/parallel.ipynb +++ b/applications/parallel/parallel.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "2b88a4ad", + "id": "2b27adf9", "metadata": {}, "source": [ "# Parallel processing in Python\n", @@ -11,16 +11,134 @@ "While Python has built-in support for threading and parallelising in the\n", "[`threading`](https://docs.python.org/3/library/threading.html) and\n", "[`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html)\n", - "modules, there are a range of third-party libraries which you can use to improve the performance of your code.\n", + "modules (covered in `advanced_programming/threading.ipynb`), there are a range of third-party libraries which you can use to improve the performance of your code.\n", "\n", "Contents:\n", "\n", + "* [Do you really need to parallelise your code?](#do-you-need-to-parallelise)\n", + " * [Profilng your code](#profiling-your-code)\n", "* [JobLib](#joblib)\n", "* [Dask](#dask)\n", " * [Dask Numpy API](#dask-numpy-api)\n", " * [Low-level Dask API](#low-level-dask-api)\n", " * [Distributing computation with Dask](#distributing-computation-with-dask)\n", "* [fsl-pipe](#fsl-pipe)\n", + "* [fsl-sub](#fsl-sub)\n", + "\n", + "\n", + "<a class=\"anchor\" id=\"do-you-need-to-parallelise\"></a>\n", + "# Do you really need to parallelise your code?\n", + "\n", + "\n", + "Before diving in and tearing your code apart, you should think very carefully about your problem, and the hardware you are using to run your code. For example, if you are processing MRI data for a number of subjects on the FMRIB cluster (where each node on the cluster has fairly modest hardware specs, meaning that within-process parallelisation will have limited benefits), the most efficient option may be to write your code in a single-threaded manner, and to parallelise across data sets, processing one data set on each cluster node.\n", + "Your best option may simply be to repeatedly call `fsl_sub`- see the [section below](#fsl-sub) for more details on this approach.\n", + "\n", + "\n", + "<a class=\"anchor\" id=\"#profiling-your-code\"></a>\n", + "## Profilng your code\n", + "\n", + "\n", + "Once you have decided that you need to parallelise some steps in your program, **STOP!** As the great Donald Knuth once said:\n", + "\n", + "> Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time:\n", + ">\n", + "> **premature optimization is the root of all evil**.\n", + ">\n", + "> Yet we should not pass up our opportunities in that critical 3%.\n", + "\n", + "\n", + "What Knuth is essentially saying is that there is no point in optimising or rewriting a piece of code unless it is actually going to have a positive impact on performance. In other words, before you refactor your code, you need to ensure that you _understand_ where the bottlenecks are, so that you know which parts of the code _should_ be re-written.\n", + "\n", + "One way in which we can find those bottlenecks is through _profiling_ - running our code, and timing each part of it, to identify which parts are causing our program to run slowly.\n", + "\n", + "As a simple example, consider this code. It is running slowly, and we want to know why:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "92119f45", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "def process_data(datafile):\n", + " data = np.loadtxt(datafile)\n", + " result = data.mean()\n", + " return result\n", + "\n", + "print(process_data('mydata.txt'))" + ] + }, + { + "cell_type": "markdown", + "id": "28a3e8e1", + "metadata": {}, + "source": [ + "> The `mydata.txt` file can be generated by running this code:\n", + ">\n", + "> ```\n", + "> import numpy as np\n", + "> data = np.random.random((10000, 1000))\n", + "> np.savetxt('mydata.txt', data)\n", + "> ```\n", + "\n", + "\n", + "For small functions, you can profile code manually by using the `time` module, e.g.:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "49fa2ba9", + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "\n", + "start = time.time()\n", + "result = process_data('mydata.txt')\n", + "end = time.time()\n", + "\n", + "print(f'Total #seconds: {end - start}')\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "id": "6c6de92c", + "metadata": {}, + "source": [ + "We could also do the same within the `process_data` function, and calculate and report the timings for each individual section within. But there is a library called `line_profiler` which can do this for you - it will time every single line of code, and print a report for you:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2413b91c", + "metadata": {}, + "outputs": [], + "source": [ + "%load_ext line_profiler\n", + "%lprun -f process_data process_data('mydata.txt')" + ] + }, + { + "cell_type": "markdown", + "id": "d3cf2572", + "metadata": {}, + "source": [ + "> `line_profiler` is not installed as part of FSL by default, but you can install it with this command:\n", + "> ```$FSLDIR/bin/conda install -p $FSLDIR line_profiler```\n", + ">\n", + "> And you can also use it from the command-line, if you are not working in a Jupyter notebook. You can learn more about `line_profiler` at https://github.com/pyutils/line_profiler\n", + "\n", + "\n", + "We can see that most of the processing time was actually in _loading_ the data from file, and not in the data _processing_ (simply calculating the mean in this toy example). Without profiling your code, you may have naively thought that the data processing step was the culprit, and needed to be optimised. But what profiling has told us here is that our problem lies elsewhere, and perhaps we need to think about changing how we are storing our data.\n", + "\n", + "\n", + "But let's assume from this point on that we _do_ need to optimise our code...\n", "\n", "\n", "<a class=\"anchor\" id=\"joblib\"></a>\n", @@ -32,7 +150,7 @@ "JobLib has been around for a while, and is a simple and lightweight library with two main features:\n", "\n", " - An API for \"embarrassingly parallel\" tasks.\n", - " - An API for caching/re-using the results of time-consuming computations.\n", + " - An API for caching/re-using the results of time-consuming computations (which we won't discuss in this notebook, but you can read about [here](https://joblib.readthedocs.io/en/stable/memory.html)).\n", "\n", "On the surface, JobLib does not provide any functionality that cannot already be accomplished with built-in libraries such as `multiprocessing` and `functools`. However, the JobLib developers have put a lot of effort into ensuring that JobLib:\n", "\n", @@ -46,7 +164,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5791f029", + "id": "0198ff8d", "metadata": {}, "outputs": [], "source": [ @@ -57,7 +175,7 @@ }, { "cell_type": "markdown", - "id": "ecf0ad57", + "id": "f64fac25", "metadata": {}, "source": [ "Now, let's say that we have a collection of `numpy` arrays containing image data for a group of subjects:" @@ -66,7 +184,7 @@ { "cell_type": "code", "execution_count": null, - "id": "53839192", + "id": "a79aacb0", "metadata": {}, "outputs": [], "source": [ @@ -75,7 +193,7 @@ }, { "cell_type": "markdown", - "id": "733f66cc", + "id": "1e30049b", "metadata": {}, "source": [ "And we want to calculate some metric on each image. We simply need to define a function which contains the calculation we want to perform (the `time.sleep` call is there just to simulate a complex calculation):" @@ -84,7 +202,7 @@ { "cell_type": "code", "execution_count": null, - "id": "049cd8dd", + "id": "ba63be7a", "metadata": {}, "outputs": [], "source": [ @@ -95,7 +213,7 @@ }, { "cell_type": "markdown", - "id": "1266287d", + "id": "d3d2b0b8", "metadata": {}, "source": [ "We can now use `joblib.Parallel` and `joblib.delayed` to parallelise those calculations. `joblib.Parallel` sets up a pool of worker processes, and `joblib.delayed` schedules a single instantiation of the function, and associated data, which is to be executed. We can execute a sequence of `delayed` tasks by passing them to the `Parallel` pool:" @@ -104,7 +222,7 @@ { "cell_type": "code", "execution_count": null, - "id": "931cb5d7", + "id": "814aef5c", "metadata": {}, "outputs": [], "source": [ @@ -116,15 +234,14 @@ }, { "cell_type": "markdown", - "id": "5b499444", + "id": "e3bd3114", "metadata": {}, "source": [ - "Just like with `multiprocessing`, JobLib is susceptible to the same problems with regard to sharing data between processes (these problems are\n", - "discussed in the `advanced_programming/threading.ipynb` notebook). In the example above, each dataset is serialised and copied from the main process\n", - "to the worker processes, and then the result copied back. This behaviour could be a performance bottleneck for your own task, or you may be working\n", - "on a system with limited memory which is incapable of storing several copies of the data.\n", + "Just like with `multiprocessing`, JobLib is susceptible to the same problems with regard to sharing data between processes (these problems are discussed in the `advanced_programming/threading.ipynb` notebook). In the example above, each dataset is serialised and copied from the main process to the worker processes, and then the result copied back. This behaviour could be a performance bottleneck for your own task, or you may be working on a system with limited memory which is incapable of storing several copies of the data.\n", + "\n", + "To deal with this, we can use memory-mapped Numpy arrays. This is a feature built into Numpy, and supported by JobLib, which invlolves storing your data in your file system instead of in memory. This allows your data to be simultaneously read and written by multiple processes.\n", "\n", - "To deal with this, we can use memory-mapped Numpy arrays. This is a feature built into Numpy, and supported by JobLib, which stores your data in your file system instead of in memory. This allows your data to be simultaneously read and written by multiple processes.\n", + "> Some other options for sharing data between processes are discussed in the `advanced_programming/threading.ipynb` notebook.\n", "\n", "You can create `numpy.memmap` arrays directly, but JobLib will also automatically convert any Numpy arrays which are larger than a specified threshold into memory-mapped arrays. This threshold defaults to 1MB, and you can change it via the `n_bytes` option when you create a `joblib.Parallel` pool.\n", "\n", @@ -134,7 +251,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6ec1fb3a", + "id": "9b7106d6", "metadata": {}, "outputs": [], "source": [ @@ -146,7 +263,7 @@ }, { "cell_type": "markdown", - "id": "314c22e5", + "id": "44eff256", "metadata": {}, "source": [ "Now we will load our 4D data, and pre-allocate another array to store the fitted model parameters." @@ -155,7 +272,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d9f90609", + "id": "2e548f25", "metadata": {}, "outputs": [], "source": [ @@ -177,7 +294,7 @@ }, { "cell_type": "markdown", - "id": "47dc9a3b", + "id": "c5a776e2", "metadata": {}, "source": [ "<a class=\"anchor\" id=\"dask\"></a>\n", @@ -190,30 +307,26 @@ "\n", "Dask has two main components:\n", "\n", - " - APIs for defining tasks/jobs - there is a low-level API similar to that provided by JobLib, but Dask also has sophisticated high-level APIs for working with Pandas and Numpy-style data.\n", + " - APIs for defining tasks/jobs - there is a low-level API comparable to that provided by JobLib, but Dask also has sophisticated high-level APIs for working with Pandas and Numpy-style data.\n", "\n", " - A task scheduler which builds a graph of all the tasks that need to be executed, and which manges their execution, either locally or remotely.\n", "\n", - "We will introduce the Numpy API and will briefly cover the low-level API, and then demonstrate how to use Dask to perform calculations on a SGE cluster.\n", + "We will introduce the Numpy API and the low-level API, and then demonstrate how to use Dask to perform calculations on a SGE cluster.\n", "\n", "\n", "<a class=\"anchor\" id=\"dask-numpy-api\"></a>\n", "## Dask Numpy API\n", "\n", - "\n", "https://docs.dask.org/en/stable/array.html\n", "\n", "\n", - "> Dask also provides a Pandas-style API, accessible in the `dask.dataframe` package - you can read about it at https://docs.dask.org/en/stable/dataframe.html.\n", - "\n", - "\n", "To use the Dask Numpy API, simply import the `dask.array` package, and use it instead of the `numpy` package:" ] }, { "cell_type": "code", "execution_count": null, - "id": "7923a7be", + "id": "10dabd47", "metadata": {}, "outputs": [], "source": [ @@ -226,15 +339,14 @@ }, { "cell_type": "markdown", - "id": "2bdd29e6", + "id": "6c7c7ecd", "metadata": {}, "source": [ "If you do the numbers, you will realise that the above call has created an array which requires **74 gigabytes** of memory - this is far more memory than what is available in most consumer level computers.\n", "\n", - "> The call would almost certainly fail if you made it using `np.random.random` instead of `da.random.random`, as Numpy will attempt to create the entire data set (and in fact would temporarily require up to **150 gigabytes** of memory, as Numpy uses double-precision floating point (`float64`) values by default).\n", + "The call would almost certainly fail if you made it using `np.random.random` instead of `da.random.random`, as Numpy would attempt to create the entire data set (and in fact would temporarily require up to **150 gigabytes** of memory, as Numpy uses double-precision floating point (`float64`) values by default).\n", "\n", - "\n", - "However:\n", + "However, this worked because:\n", "\n", " - Dask automatically splits arrays into smaller chunks - in the above code, `data` has been split into 1331 smaller arrays, each of which has shape `(94, 94, 94, 10)`, and requires only 64 megabytes.\n", "\n", @@ -246,7 +358,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b2605c92", + "id": "724334d6", "metadata": {}, "outputs": [], "source": [ @@ -256,7 +368,7 @@ }, { "cell_type": "markdown", - "id": "08bf1c77", + "id": "98438c67", "metadata": {}, "source": [ "But again, this will not actually calculate the mean - it just defines a task which, when executed, will calculate the mean over the `data` array.\n", @@ -267,7 +379,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cecf0b61", + "id": "fe23c705", "metadata": {}, "outputs": [], "source": [ @@ -276,10 +388,13 @@ }, { "cell_type": "markdown", - "id": "1472b53d", + "id": "e558f8cb", "metadata": {}, "source": [ - "Dask arrays support most of the functionality of Numpy arrays, but there are a few exceptions, most notably the `numpy.linalg` package.\n", + "Dask arrays support _most_ of the functionality of Numpy arrays, but there are a few exceptions, most notably the `numpy.linalg` package.\n", + "\n", + "\n", + "> Remember that Dask also provides a Pandas-style API, accessible in the `dask.dataframe` package - you can read about it at https://docs.dask.org/en/stable/dataframe.html.\n", "\n", "\n", "<a class=\"anchor\" id=\"low-level-dask-api\"></a>\n", @@ -294,7 +409,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1f764830", + "id": "9c3acf29", "metadata": {}, "outputs": [], "source": [ @@ -310,7 +425,7 @@ }, { "cell_type": "markdown", - "id": "fd5252f6", + "id": "09c6f537", "metadata": {}, "source": [ "We could solve this problem without parallelism by using conventional Python code, which might look something like the following:" @@ -319,7 +434,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b0910aaf", + "id": "77e896a4", "metadata": {}, "outputs": [], "source": [ @@ -336,7 +451,7 @@ }, { "cell_type": "markdown", - "id": "8a7a45f5", + "id": "b731893c", "metadata": {}, "source": [ "However, this problem is inherently parallelisable - we are independently performing the same series of steps to each of our inputs, before the final tallying. We can use the `dask.delayed` function to take advantage of this:" @@ -345,7 +460,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9031f120", + "id": "a79b728e", "metadata": {}, "outputs": [], "source": [ @@ -361,16 +476,16 @@ }, { "cell_type": "markdown", - "id": "6bc3ef4c", + "id": "1cccc09a", "metadata": {}, "source": [ - "We have not actually performed any computations yet. What we have done is built a _graph_ of operations that we need to perform. Dask refers to this as a **task graph** - Dask keeps track of the dependencies of each function that we add, and so is able to determine the order in they need to be executed, and also which steps do not depend on each other and so can be executed in parallel. Dask can even generate an image of our task graph for us:" + "We have not actually performed any computations yet. What we have done is built a _graph_ of operations that we need to perform. Dask refers to this as a **task graph**. Dask keeps track of the dependencies of each function that we add, and so is able to determine the order in they need to be executed, and also which steps do not depend on each other and so can be executed in parallel. Dask can even visualise this task graph for us:" ] }, { "cell_type": "code", "execution_count": null, - "id": "9f0833d9", + "id": "8d9b95b0", "metadata": {}, "outputs": [], "source": [ @@ -379,7 +494,7 @@ }, { "cell_type": "markdown", - "id": "0164c407", + "id": "9c387b05", "metadata": {}, "source": [ "And then when we are ready, we can call `compute()` to actually do the calculation:" @@ -388,7 +503,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8561997b", + "id": "f5d1d09c", "metadata": {}, "outputs": [], "source": [ @@ -397,16 +512,16 @@ }, { "cell_type": "markdown", - "id": "3590a9f9", + "id": "c1c95d5f", "metadata": {}, "source": [ - "For a more realistic example, let's imagine that we have T1 MRI images for five subjects, and we want to perform basic structural preprocessing on each of them (reorientation, FOV reduction, and brain extraction). He're creating this example data set (all of the T1 images are just a copy of the `bighead.nii.gz` image, from the FSL course data)." + "For a more realistic example, let's imagine that we have T1 MRI images for five subjects, and we want to perform basic structural preprocessing on each of them (reorientation, FOV reduction, and brain extraction). Here we're creating this example data set (all of the T1 images are just a copy of the `bighead.nii.gz` image, from the FSL course data)." ] }, { "cell_type": "code", "execution_count": null, - "id": "c3879db5", + "id": "f6f614f2", "metadata": {}, "outputs": [], "source": [ @@ -420,16 +535,19 @@ }, { "cell_type": "markdown", - "id": "77851c91", + "id": "ababc17d", "metadata": {}, "source": [ - "And now we can build our pipeline. The [fslpy](https://open.win.ox.ac.uk/pages/fsl/fslpy/) library has a collection of functions which we can use to call the FSL commands that we need. We need to do a little work, as by default `dask.delayed` assumes that the dependencies of a task are passed in as arguments (there are other ways of dealing with this, but in this example it is easy to simply write a few small functions that define each of our tasks):" + "And now we can build our pipeline. The [fslpy](https://open.win.ox.ac.uk/pages/fsl/fslpy/) library has a collection of functions which we can use to call the FSL commands that we need.\n", + "\n", + "\n", + "We need to do a little work, as by default `dask.delayed` assumes that the dependencies of a function (i.e. other `delayed` functions) are passed to the function as arguments. There are [other methods](https://docs.dask.org/en/stable/delayed.html#indirect-dependencies) of dealing with this, but often the easiest option is simply to write a few small functions that define each of our tasks, in a manner that satisfies this assumption:" ] }, { "cell_type": "code", "execution_count": null, - "id": "1f9d5f36", + "id": "fe917598", "metadata": {}, "outputs": [], "source": [ @@ -448,10 +566,18 @@ " return output" ] }, + { + "cell_type": "markdown", + "id": "a1cd4b06", + "metadata": {}, + "source": [ + "Again we use `dask.delayed` to build up a graph of tasks that need executing, starting from the input files, and ending with our final brain-extracted outputs. Again, we are not actually executing anything here - we're just building up a task graph that Dask will then execute for us later:" + ] + }, { "cell_type": "code", "execution_count": null, - "id": "4a762719", + "id": "d03c2ae2", "metadata": {}, "outputs": [], "source": [ @@ -472,16 +598,16 @@ }, { "cell_type": "markdown", - "id": "1ed04761", + "id": "e0215eaf", "metadata": {}, "source": [ - "In the previous example we had a single output (the result of summing the squared input values) which we called `visualize()` on. We can also call `dask.visualize()` to visualise a collection of tasks:" + "In the previous example we had a single output (the result of summing the squared input values) upon which we called `visualize()`. Here we have a list of independent tasks (in the `tasks` list). However, we can still visualise them by passing the entire list to the `dask.visualize()` function:" ] }, { "cell_type": "code", "execution_count": null, - "id": "f62c7c6d", + "id": "a08d0d91", "metadata": {}, "outputs": [], "source": [ @@ -490,16 +616,16 @@ }, { "cell_type": "markdown", - "id": "63017c42", + "id": "244a2ae9", "metadata": {}, "source": [ - "And, similarly, we can call `dask.compute` to run them all:" + "And, similarly, we can call `dask.compute` to run them all at once:" ] }, { "cell_type": "code", "execution_count": null, - "id": "7b6e40a9", + "id": "6b98bb2a", "metadata": {}, "outputs": [], "source": [ @@ -509,14 +635,14 @@ }, { "cell_type": "markdown", - "id": "5dbb82f6", + "id": "6d77a9f8", "metadata": {}, "source": [ "<a class=\"anchor\" id=\"distributing-computation-with-dask\"></a>\n", "## Distributing computation with Dask\n", "\n", "\n", - "In the examples above, Dask was running its tasks in parallel on your local machine. But it is easy to instruct Dask to distribute its computations across multiple machines. For example, Dask has support for executing tasks on a SGE or SLURM cluster, which we have available in Oxford at FMRIB and the BDI.\n", + "In the examples above, Dask was running your tasks in parallel on your local machine. But it is easy to instruct Dask to distribute your computations across multiple machines. For example, Dask has support for executing tasks on a SGE or SLURM cluster, which we have available in Oxford at FMRIB and the BDI.\n", "\n", "To use this functionality, we need an additional library called `dask-jobqueue` which, at the moment, is not installed as part of FSL.\n", "\n", @@ -529,7 +655,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b6e7814e", + "id": "e206a399", "metadata": {}, "outputs": [], "source": [ @@ -539,7 +665,7 @@ }, { "cell_type": "markdown", - "id": "10dd646c", + "id": "a69e8eaa", "metadata": {}, "source": [ "You can also set a range of other options, including specifying a queue name (e.g. `queue='short.q'`), or specifying the total amount of time that your job will run for (e.g. `walltime='01:00:00'` for one hour).\n", @@ -551,7 +677,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bfa74705", + "id": "20c0da1a", "metadata": {}, "outputs": [], "source": [ @@ -560,7 +686,7 @@ }, { "cell_type": "markdown", - "id": "7123a281", + "id": "96c05bcd", "metadata": {}, "source": [ "Behind the scenes, the `scale()` method uses `qsub` to create five \"worker processes\", each running on a different cluster node. In the first instance, these worker processes will be sitting idle, doing nothing, and waiting for you to give them a task to run.\n", @@ -571,7 +697,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0c8502aa", + "id": "e3742ee0", "metadata": {}, "outputs": [], "source": [ @@ -580,7 +706,7 @@ }, { "cell_type": "markdown", - "id": "9b43cee7", + "id": "d4053813", "metadata": {}, "source": [ "After creating a client, any Dask computations that we request will be performed on the cluster by our worker processes:" @@ -589,7 +715,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c06367ee", + "id": "2b8fc2c0", "metadata": {}, "outputs": [], "source": [ @@ -600,11 +726,11 @@ }, { "cell_type": "markdown", - "id": "f5c78ed3", + "id": "e0e99795", "metadata": {}, "source": [ "<a class=\"anchor\" id=\"fsl-pipe\"></a>\n", - "## fsl-pipe\n", + "# fsl-pipe\n", "\n", "\n", "https://open.win.ox.ac.uk/pages/fsl/fsl-pipe/\n", @@ -612,13 +738,13 @@ "\n", "fsl-pipe is a Python library (written by our very own Michiel Cottaar) which builds upon another library called [file-tree](https://open.win.ox.ac.uk/pages/fsl/file-tree/), and allows you to write an analysis pipeline in a _declarative_ manner. A pipeline is defined by:\n", "\n", - " - A \"file tree\" which defines the directory structure of the input and output files of the pipeline.\n", - " - A set of recipes (Python functions) describing how each of the pipeline outputs should be produced.\n", + " - A _file tree_ which defines the directory structure of the input and output files of the pipeline.\n", + " - A set of _recipes_ (Python functions) describing how each of the pipeline outputs should be produced.\n", "\n", - "In a similar vein to Dask task graphs, fsl-pipe will automatically determine which recipes should be executed, and in what order, to produce whichever output file(s) you request. Recipes can either run locally, be distributed using Dask, or be executed on a cluster using `fsl_sub`.\n", + "In a similar vein to [Dask task graphs](#low-level-dask-api), fsl-pipe will automatically determine which recipes should be executed, and in what order, to produce whichever output file(s) you request. You can instruct fsl-pipe to run your recipes locally, be parallelised or distributed using Dask, or be executed on a cluster using `fsl_sub`.\n", "\n", "\n", - "For example, let's again imagine that we have some T1 images upon which we wish to perform basic structural preprocessing, and which arranged in the following manner:\n", + "For example, let's again imagine that we have some T1 images upon which we wish to perform basic structural preprocessing, and which are arranged in the following manner:\n", "\n", "> ```\n", "> subjectA/\n", @@ -629,37 +755,252 @@ "> T1w.nii.gz\n", "> ```\n", "\n", - "We must first describe the structure of our data, and save that description as a file-tree file (e.g. `mydata.tree`). This file contains a placeholder for the subject ID, and gives both the input and any desired output files unique identifiers:\n", + "The code cell below will automatically create a dummy data set with the above structure:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4d42fa32", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import shutil\n", "\n", - "> ```\n", - "> subject{subject}\n", - "> T1w.nii.gz (t1)\n", - "> T1w_brain.nii.gz (t1_brain)\n", - "> T1w_fov.nii.gz (t1_fov)\n", - "> T1w_reorient.nii.gz (t1_reorient)\n", - "> ```" + "for subj in 'ABC':\n", + " subjdir = f'mydata/subject{subj}'\n", + " os.makedirs(subjdir, exist_ok=True)\n", + " shutil.copy('../../applications/fslpy/bighead.nii.gz', f'{subjdir}/T1w.nii.gz')" + ] + }, + { + "cell_type": "markdown", + "id": "01575655", + "metadata": {}, + "source": [ + "We must first describe the structure of our data, and save that description as a file-tree file (e.g. `mydata.tree`). This file contains a placeholder for the subject ID, and gives both the input and any desired output files unique identifiers:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4de54ba7", + "metadata": {}, + "outputs": [], + "source": [ + "%%writefile mydata.tree\n", + "subject{subject}\n", + " T1w.nii.gz (t1)\n", + " T1w_brain.nii.gz (t1_brain)\n", + " T1w_fov.nii.gz (t1_fov)\n", + " T1w_reorient.nii.gz (t1_reorient)" + ] + }, + { + "cell_type": "markdown", + "id": "99006f8c", + "metadata": {}, + "source": [ + "Now we need to define our _recipes_, the individual processing steps that we want to perform, and that will generate our output files. This is similar to what we did above when we were using [Dask](#low-level-dask-api) - we define functions which perform each step." ] }, { "cell_type": "code", "execution_count": null, - "id": "07ff84b0", + "id": "819900fa", "metadata": {}, "outputs": [], "source": [ - "#!/usr/bin/env python\n", + "from fsl.wrappers import bet, fslreorient2std, robustfov\n", + "from fsl_pipe import Pipeline, In, Out\n", "\n", - "from fsl.wrappers import bet\n", + "def reorient(t1 : In, t1_reorient : Out):\n", + " fslreorient2std(t1, t1_reorient)\n", + "\n", + "def fov(t1_reorient : In, t1_fov : Out):\n", + " robustfov(t1_reorient, t1_fov)\n", + "\n", + "def brain_extract(t1_fov : In, t1_brain : Out):\n", + " bet(t1_fov, t1_brain)" + ] + }, + { + "cell_type": "markdown", + "id": "91375ad3", + "metadata": {}, + "source": [ + "Note that we have also annotated the inputs and outputs of each function, and have used the same identifiers that we used in our `mydata.tree` file above. By doing this, `fsl-pipe` is automatically able to determine the steps that would be required in order to generate the output files that we request.\n", + "\n", + "Once we have defined all of our recipes, we need to create a `Pipeline` object, and add all of our functions to it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "25e48fd7", + "metadata": {}, + "outputs": [], + "source": [ + "pipe = Pipeline()\n", + "pipe(reorient)\n", + "pipe(fov)\n", + "pipe(brain_extract)" + ] + }, + { + "cell_type": "markdown", + "id": "d1d5024f", + "metadata": {}, + "source": [ + "> Note that it is also possible (and equivalent) to create the `Pipeline` before defining our recipe functions, and to use the pipeline as a decorator, e.g.:\n", + ">\n", + "> ```\n", + "> pipe = Pipeline()\n", + ">\n", + "> @pipe\n", + "> def reorient(t1 : In, t1_reorient : Out):\n", + "> ...\n", + "> ```\n", + ">\n", "\n", + "\n", + "We now need to create a `FileTree` object which is used to generate file paths for the input and output files. The `update_glob('t1')` method instructs the `FileTree` to scan the file system, and to generate file paths for all T1 images that are present." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9d49246c", + "metadata": {}, + "outputs": [], + "source": [ "from file_tree import FileTree\n", - "from fsl_pipe import pipe, In, Out\n", + "tree = FileTree.read('mydata.tree', './mydata/').update_glob('t1')" + ] + }, + { + "cell_type": "markdown", + "id": "84d9df1f", + "metadata": {}, + "source": [ + "Then it is very easy to run our pipeline:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0c92b06", + "metadata": {}, + "outputs": [], + "source": [ + "jobs = pipe.generate_jobs(tree)\n", + "jobs.run()" + ] + }, + { + "cell_type": "markdown", + "id": "e486a07f", + "metadata": {}, + "source": [ + "The default behaviour when using fsl-pipe locally is to for one task to be executed at a time. However, if you run fsl-pipe on the cluster, it will automatically submit the jobs using `fsl_sub`. You can also tell fsl-pipe to execute the pipeline using Dask, which will cause any independent jobs to be executed in parallel, e.g.:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a61d7603", + "metadata": {}, + "outputs": [], + "source": [ + "jobs.run(method='dask')" + ] + }, + { + "cell_type": "markdown", + "id": "458be3fe", + "metadata": {}, + "source": [ + "The above example is just one way of using fsl-pipe - the library has several powerful features, including its own command-line interface, and the ability to skip jobs for output files that already exist.\n", + "\n", + "\n", + "<a class=\"anchor\" id=\"fsl-sub\"></a>\n", + "## fsl-sub\n", + "\n", + "\n", + "You can use the venerable `fsl_sub` to run several tasks in parallel both on your local machine, and on a HPC cluster, such as the ones available to us at FMRIB and the BDI. `fsl_sub` is typically called from the command-line, e.g.:\n", + "\n", + "> ```\n", + "> for dataset in mydata/sub-*; do\n", + "> fsl_sub ./my_processing_script.py ${dataset} --jobram 16\n", + "> done\n", + "> ```\n", + "\n", + "\n", + "If you are working on a local machine, `fsl_sub` will block until your command has completed. You can run multiple commands in parallel by using \"array tasks\" - save each of the commands you want to run to a text file, e.g.:\n", + "\n", + "> ```\n", + "> echo \"./my_processing_script.py mydata/sub-01\" > tasks.txt\n", + "> echo \"./my_processing_script.py mydata/sub-02\" >> tasks.txt\n", + "> echo \"./my_processing_script.py mydata/sub-03\" >> tasks.txt\n", + "> echo \"./my_processing_script.py mydata/sub-04\" >> tasks.txt\n", + "> echo \"./my_processing_script.py mydata/sub-05\" >> tasks.txt\n", + "> ```\n", + "\n", + "And then run `fsl_sub -t tasks.txt` - each of your commands will be executed in parallel. If you are working on a cluster, `fsl_sub` will schedule all of the commands to be executed simultaneously.\n", "\n", - "@pipe\n", - "def brain_extract(t1 : In, bet_output : Out, bet_mask : Out):\n", - " bet(t1, bet_output, mask=True)\n", + "You can also call `fsl_sub` from Python by using functions from the `fslpy` library:\n", + "\n", + "> ```\n", + "> from glob import glob\n", + "> from fsl.wrappers import fsl_sub\n", + ">\n", + "> for dataset in glob('mydata/sub-*'):\n", + "> fsl_sub(f'./my_processing_script.py ${dataset}', jobram=16)\n", + "> ```\n", + "\n", + "And the `fslpy` wrapper functions allow you to run FSL commands with `fsl_sub`, and to specify job dependencies. For example, to submit a collection of jobs, you can pass `submit=True`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "37134ca6", + "metadata": {}, + "outputs": [], + "source": [ + "from fsl.data.image import removeExt\n", + "from fsl.wrappers import bet\n", + "from glob import glob\n", + "\n", + "for t1 in glob('braindata/??.nii.gz'):\n", + " t1 = removeExt(t1)\n", + " bet(t1, f'{t1}_brain', submit={'jobram':16})" + ] + }, + { + "cell_type": "markdown", + "id": "681b1a8c", + "metadata": {}, + "source": [ + "You can also specify dependencies by using the ID of a previously submitted job, e.g.:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e7c2329c", + "metadata": {}, + "outputs": [], + "source": [ + "from fsl.data.image import removeExt\n", + "from fsl.wrappers import robustfov, bet\n", + "from glob import glob\n", "\n", - "tree = FileTree.read('data.tree').update_glob('t1')\n", - "pipe.cli(tree)" + "for t1 in glob('braindata/??.nii.gz'):\n", + " t1 = removeExt(t1)\n", + " jid = robustfov(t1, f'{t1}_fov', submit=True)\n", + " bet(f'{t1}_fov', f'{t1}_brain', submit={'jobram':16, 'jobhold' : jid})" ] } ], diff --git a/applications/parallel/parallel.md b/applications/parallel/parallel.md index 005c7aa569df5dc5d4167c510b59f9708f71ad73..d51a17c7fe968ed9fc8abaa4fa316bfbb150bb4b 100644 --- a/applications/parallel/parallel.md +++ b/applications/parallel/parallel.md @@ -4,16 +4,104 @@ While Python has built-in support for threading and parallelising in the [`threading`](https://docs.python.org/3/library/threading.html) and [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html) -modules, there are a range of third-party libraries which you can use to improve the performance of your code. +modules (covered in `advanced_programming/threading.ipynb`), there are a range of third-party libraries which you can use to improve the performance of your code. Contents: +* [Do you really need to parallelise your code?](#do-you-need-to-parallelise) + * [Profilng your code](#profiling-your-code) * [JobLib](#joblib) * [Dask](#dask) * [Dask Numpy API](#dask-numpy-api) * [Low-level Dask API](#low-level-dask-api) * [Distributing computation with Dask](#distributing-computation-with-dask) * [fsl-pipe](#fsl-pipe) +* [fsl-sub](#fsl-sub) + + +<a class="anchor" id="do-you-need-to-parallelise"></a> +# Do you really need to parallelise your code? + + +Before diving in and tearing your code apart, you should think very carefully about your problem, and the hardware you are using to run your code. For example, if you are processing MRI data for a number of subjects on the FMRIB cluster (where each node on the cluster has fairly modest hardware specs, meaning that within-process parallelisation will have limited benefits), the most efficient option may be to write your code in a single-threaded manner, and to parallelise across data sets, processing one data set on each cluster node. +Your best option may simply be to repeatedly call `fsl_sub`- see the [section below](#fsl-sub) for more details on this approach. + + +<a class="anchor" id="#profiling-your-code"></a> +## Profilng your code + + +Once you have decided that you need to parallelise some steps in your program, **STOP!** As the great Donald Knuth once said: + +> Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: +> +> **premature optimization is the root of all evil**. +> +> Yet we should not pass up our opportunities in that critical 3%. + + +What Knuth is essentially saying is that there is no point in optimising or rewriting a piece of code unless it is actually going to have a positive impact on performance. In other words, before you refactor your code, you need to ensure that you _understand_ where the bottlenecks are, so that you know which parts of the code _should_ be re-written. + +One way in which we can find those bottlenecks is through _profiling_ - running our code, and timing each part of it, to identify which parts are causing our program to run slowly. + +As a simple example, consider this code. It is running slowly, and we want to know why: + + +``` +import numpy as np + +def process_data(datafile): + data = np.loadtxt(datafile) + result = data.mean() + return result + +print(process_data('mydata.txt')) +``` + + +> The `mydata.txt` file can be generated by running this code: +> +> ``` +> import numpy as np +> data = np.random.random((10000, 1000)) +> np.savetxt('mydata.txt', data) +> ``` + + +For small functions, you can profile code manually by using the `time` module, e.g.: + + +``` +import time + +start = time.time() +result = process_data('mydata.txt') +end = time.time() + +print(f'Total #seconds: {end - start}') +print(result) +``` + + +We could also do the same within the `process_data` function, and calculate and report the timings for each individual section within. But there is a library called `line_profiler` which can do this for you - it will time every single line of code, and print a report for you: + + +``` +%load_ext line_profiler +%lprun -f process_data process_data('mydata.txt') +``` + + +> `line_profiler` is not installed as part of FSL by default, but you can install it with this command: +> ```$FSLDIR/bin/conda install -p $FSLDIR line_profiler``` +> +> And you can also use it from the command-line, if you are not working in a Jupyter notebook. You can learn more about `line_profiler` at https://github.com/pyutils/line_profiler + + +We can see that most of the processing time was actually in _loading_ the data from file, and not in the data _processing_ (simply calculating the mean in this toy example). Without profiling your code, you may have naively thought that the data processing step was the culprit, and needed to be optimised. But what profiling has told us here is that our problem lies elsewhere, and perhaps we need to think about changing how we are storing our data. + + +But let's assume from this point on that we _do_ need to optimise our code... <a class="anchor" id="joblib"></a> @@ -25,7 +113,7 @@ https://joblib.readthedocs.io/en/stable/ JobLib has been around for a while, and is a simple and lightweight library with two main features: - An API for "embarrassingly parallel" tasks. - - An API for caching/re-using the results of time-consuming computations. + - An API for caching/re-using the results of time-consuming computations (which we won't discuss in this notebook, but you can read about [here](https://joblib.readthedocs.io/en/stable/memory.html)). On the surface, JobLib does not provide any functionality that cannot already be accomplished with built-in libraries such as `multiprocessing` and `functools`. However, the JobLib developers have put a lot of effort into ensuring that JobLib: @@ -66,12 +154,11 @@ with joblib.Parallel(n_jobs=-1) as pool: print(results) ``` -Just like with `multiprocessing`, JobLib is susceptible to the same problems with regard to sharing data between processes (these problems are -discussed in the `advanced_programming/threading.ipynb` notebook). In the example above, each dataset is serialised and copied from the main process -to the worker processes, and then the result copied back. This behaviour could be a performance bottleneck for your own task, or you may be working -on a system with limited memory which is incapable of storing several copies of the data. +Just like with `multiprocessing`, JobLib is susceptible to the same problems with regard to sharing data between processes (these problems are discussed in the `advanced_programming/threading.ipynb` notebook). In the example above, each dataset is serialised and copied from the main process to the worker processes, and then the result copied back. This behaviour could be a performance bottleneck for your own task, or you may be working on a system with limited memory which is incapable of storing several copies of the data. -To deal with this, we can use memory-mapped Numpy arrays. This is a feature built into Numpy, and supported by JobLib, which stores your data in your file system instead of in memory. This allows your data to be simultaneously read and written by multiple processes. +To deal with this, we can use memory-mapped Numpy arrays. This is a feature built into Numpy, and supported by JobLib, which invlolves storing your data in your file system instead of in memory. This allows your data to be simultaneously read and written by multiple processes. + +> Some other options for sharing data between processes are discussed in the `advanced_programming/threading.ipynb` notebook. You can create `numpy.memmap` arrays directly, but JobLib will also automatically convert any Numpy arrays which are larger than a specified threshold into memory-mapped arrays. This threshold defaults to 1MB, and you can change it via the `n_bytes` option when you create a `joblib.Parallel` pool. @@ -115,23 +202,19 @@ Dask is a very powerful library which you can use to parallelise your code, and Dask has two main components: - - APIs for defining tasks/jobs - there is a low-level API similar to that provided by JobLib, but Dask also has sophisticated high-level APIs for working with Pandas and Numpy-style data. + - APIs for defining tasks/jobs - there is a low-level API comparable to that provided by JobLib, but Dask also has sophisticated high-level APIs for working with Pandas and Numpy-style data. - A task scheduler which builds a graph of all the tasks that need to be executed, and which manges their execution, either locally or remotely. -We will introduce the Numpy API and will briefly cover the low-level API, and then demonstrate how to use Dask to perform calculations on a SGE cluster. +We will introduce the Numpy API and the low-level API, and then demonstrate how to use Dask to perform calculations on a SGE cluster. <a class="anchor" id="dask-numpy-api"></a> ## Dask Numpy API - https://docs.dask.org/en/stable/array.html -> Dask also provides a Pandas-style API, accessible in the `dask.dataframe` package - you can read about it at https://docs.dask.org/en/stable/dataframe.html. - - To use the Dask Numpy API, simply import the `dask.array` package, and use it instead of the `numpy` package: ``` @@ -144,10 +227,9 @@ data If you do the numbers, you will realise that the above call has created an array which requires **74 gigabytes** of memory - this is far more memory than what is available in most consumer level computers. -> The call would almost certainly fail if you made it using `np.random.random` instead of `da.random.random`, as Numpy will attempt to create the entire data set (and in fact would temporarily require up to **150 gigabytes** of memory, as Numpy uses double-precision floating point (`float64`) values by default). +The call would almost certainly fail if you made it using `np.random.random` instead of `da.random.random`, as Numpy would attempt to create the entire data set (and in fact would temporarily require up to **150 gigabytes** of memory, as Numpy uses double-precision floating point (`float64`) values by default). - -However: +However, this worked because: - Dask automatically splits arrays into smaller chunks - in the above code, `data` has been split into 1331 smaller arrays, each of which has shape `(94, 94, 94, 10)`, and requires only 64 megabytes. @@ -170,7 +252,10 @@ print(m.compute()) ``` -Dask arrays support most of the functionality of Numpy arrays, but there are a few exceptions, most notably the `numpy.linalg` package. +Dask arrays support _most_ of the functionality of Numpy arrays, but there are a few exceptions, most notably the `numpy.linalg` package. + + +> Remember that Dask also provides a Pandas-style API, accessible in the `dask.dataframe` package - you can read about it at https://docs.dask.org/en/stable/dataframe.html. <a class="anchor" id="low-level-dask-api"></a> @@ -220,7 +305,7 @@ for x in data: total = dask.delayed(sum)(output) ``` -We have not actually performed any computations yet. What we have done is built a _graph_ of operations that we need to perform. Dask refers to this as a **task graph** - Dask keeps track of the dependencies of each function that we add, and so is able to determine the order in they need to be executed, and also which steps do not depend on each other and so can be executed in parallel. Dask can even generate an image of our task graph for us: +We have not actually performed any computations yet. What we have done is built a _graph_ of operations that we need to perform. Dask refers to this as a **task graph**. Dask keeps track of the dependencies of each function that we add, and so is able to determine the order in they need to be executed, and also which steps do not depend on each other and so can be executed in parallel. Dask can even visualise this task graph for us: ``` total.visualize() @@ -233,7 +318,7 @@ total.compute() ``` -For a more realistic example, let's imagine that we have T1 MRI images for five subjects, and we want to perform basic structural preprocessing on each of them (reorientation, FOV reduction, and brain extraction). He're creating this example data set (all of the T1 images are just a copy of the `bighead.nii.gz` image, from the FSL course data). +For a more realistic example, let's imagine that we have T1 MRI images for five subjects, and we want to perform basic structural preprocessing on each of them (reorientation, FOV reduction, and brain extraction). Here we're creating this example data set (all of the T1 images are just a copy of the `bighead.nii.gz` image, from the FSL course data). ``` @@ -245,7 +330,10 @@ for i in range(1, 6): shutil.copy('../../applications/fslpy/bighead.nii.gz', f'braindata/{i:02d}.nii.gz') ``` -And now we can build our pipeline. The [fslpy](https://open.win.ox.ac.uk/pages/fsl/fslpy/) library has a collection of functions which we can use to call the FSL commands that we need. We need to do a little work, as by default `dask.delayed` assumes that the dependencies of a task are passed in as arguments (there are other ways of dealing with this, but in this example it is easy to simply write a few small functions that define each of our tasks): +And now we can build our pipeline. The [fslpy](https://open.win.ox.ac.uk/pages/fsl/fslpy/) library has a collection of functions which we can use to call the FSL commands that we need. + + +We need to do a little work, as by default `dask.delayed` assumes that the dependencies of a function (i.e. other `delayed` functions) are passed to the function as arguments. There are [other methods](https://docs.dask.org/en/stable/delayed.html#indirect-dependencies) of dealing with this, but often the easiest option is simply to write a few small functions that define each of our tasks, in a manner that satisfies this assumption: ``` @@ -264,6 +352,7 @@ def bet(input, output): return output ``` +Again we use `dask.delayed` to build up a graph of tasks that need executing, starting from the input files, and ending with our final brain-extracted outputs. Again, we are not actually executing anything here - we're just building up a task graph that Dask will then execute for us later: ``` import glob @@ -281,13 +370,13 @@ for input in inputs: tasks.append(b) ``` -In the previous example we had a single output (the result of summing the squared input values) which we called `visualize()` on. We can also call `dask.visualize()` to visualise a collection of tasks: +In the previous example we had a single output (the result of summing the squared input values) upon which we called `visualize()`. Here we have a list of independent tasks (in the `tasks` list). However, we can still visualise them by passing the entire list to the `dask.visualize()` function: ``` dask.visualize(*tasks) ``` -And, similarly, we can call `dask.compute` to run them all: +And, similarly, we can call `dask.compute` to run them all at once: ``` outputs = dask.compute(*tasks) @@ -299,7 +388,7 @@ print(outputs) ## Distributing computation with Dask -In the examples above, Dask was running its tasks in parallel on your local machine. But it is easy to instruct Dask to distribute its computations across multiple machines. For example, Dask has support for executing tasks on a SGE or SLURM cluster, which we have available in Oxford at FMRIB and the BDI. +In the examples above, Dask was running your tasks in parallel on your local machine. But it is easy to instruct Dask to distribute your computations across multiple machines. For example, Dask has support for executing tasks on a SGE or SLURM cluster, which we have available in Oxford at FMRIB and the BDI. To use this functionality, we need an additional library called `dask-jobqueue` which, at the moment, is not installed as part of FSL. @@ -339,8 +428,9 @@ data = da.random.random((1000, 1000, 1000, 10)) print(data.mean().compute()) ``` + <a class="anchor" id="fsl-pipe"></a> -## fsl-pipe +# fsl-pipe https://open.win.ox.ac.uk/pages/fsl/fsl-pipe/ @@ -348,13 +438,13 @@ https://open.win.ox.ac.uk/pages/fsl/fsl-pipe/ fsl-pipe is a Python library (written by our very own Michiel Cottaar) which builds upon another library called [file-tree](https://open.win.ox.ac.uk/pages/fsl/file-tree/), and allows you to write an analysis pipeline in a _declarative_ manner. A pipeline is defined by: - - A "file tree" which defines the directory structure of the input and output files of the pipeline. - - A set of recipes (Python functions) describing how each of the pipeline outputs should be produced. + - A _file tree_ which defines the directory structure of the input and output files of the pipeline. + - A set of _recipes_ (Python functions) describing how each of the pipeline outputs should be produced. -In a similar vein to Dask task graphs, fsl-pipe will automatically determine which recipes should be executed, and in what order, to produce whichever output file(s) you request. Recipes can either run locally, be distributed using Dask, or be executed on a cluster using `fsl_sub`. +In a similar vein to [Dask task graphs](#low-level-dask-api), fsl-pipe will automatically determine which recipes should be executed, and in what order, to produce whichever output file(s) you request. You can instruct fsl-pipe to run your recipes locally, be parallelised or distributed using Dask, or be executed on a cluster using `fsl_sub`. -For example, let's again imagine that we have some T1 images upon which we wish to perform basic structural preprocessing, and which arranged in the following manner: +For example, let's again imagine that we have some T1 images upon which we wish to perform basic structural preprocessing, and which are arranged in the following manner: > ``` > subjectA/ @@ -365,28 +455,157 @@ For example, let's again imagine that we have some T1 images upon which we wish > T1w.nii.gz > ``` +The code cell below will automatically create a dummy data set with the above structure: + + +``` +import os +import shutil + +for subj in 'ABC': + subjdir = f'mydata/subject{subj}' + os.makedirs(subjdir, exist_ok=True) + shutil.copy('../../applications/fslpy/bighead.nii.gz', f'{subjdir}/T1w.nii.gz') +``` + + We must first describe the structure of our data, and save that description as a file-tree file (e.g. `mydata.tree`). This file contains a placeholder for the subject ID, and gives both the input and any desired output files unique identifiers: + +``` +%%writefile mydata.tree +subject{subject} + T1w.nii.gz (t1) + T1w_brain.nii.gz (t1_brain) + T1w_fov.nii.gz (t1_fov) + T1w_reorient.nii.gz (t1_reorient) +``` + + +Now we need to define our _recipes_, the individual processing steps that we want to perform, and that will generate our output files. This is similar to what we did above when we were using [Dask](#low-level-dask-api) - we define functions which perform each step. + +``` +from fsl.wrappers import bet, fslreorient2std, robustfov +from fsl_pipe import Pipeline, In, Out + +def reorient(t1 : In, t1_reorient : Out): + fslreorient2std(t1, t1_reorient) + +def fov(t1_reorient : In, t1_fov : Out): + robustfov(t1_reorient, t1_fov) + +def brain_extract(t1_fov : In, t1_brain : Out): + bet(t1_fov, t1_brain) +``` + +Note that we have also annotated the inputs and outputs of each function, and have used the same identifiers that we used in our `mydata.tree` file above. By doing this, `fsl-pipe` is automatically able to determine the steps that would be required in order to generate the output files that we request. + +Once we have defined all of our recipes, we need to create a `Pipeline` object, and add all of our functions to it: + + +``` +pipe = Pipeline() +pipe(reorient) +pipe(fov) +pipe(brain_extract) +``` + + +> Note that it is also possible (and equivalent) to create the `Pipeline` before defining our recipe functions, and to use the pipeline as a decorator, e.g.: +> > ``` -> subject{subject} -> T1w.nii.gz (t1) -> T1w_brain.nii.gz (t1_brain) -> T1w_fov.nii.gz (t1_fov) -> T1w_reorient.nii.gz (t1_reorient) +> pipe = Pipeline() +> +> @pipe +> def reorient(t1 : In, t1_reorient : Out): +> ... > ``` +> + + +We now need to create a `FileTree` object which is used to generate file paths for the input and output files. The `update_glob('t1')` method instructs the `FileTree` to scan the file system, and to generate file paths for all T1 images that are present. + ``` -#!/usr/bin/env python +from file_tree import FileTree +tree = FileTree.read('mydata.tree', './mydata/').update_glob('t1') +``` + +Then it is very easy to run our pipeline: + +``` +jobs = pipe.generate_jobs(tree) +jobs.run() +``` + +The default behaviour when using fsl-pipe locally is to for one task to be executed at a time. However, if you run fsl-pipe on the cluster, it will automatically submit the jobs using `fsl_sub`. You can also tell fsl-pipe to execute the pipeline using Dask, which will cause any independent jobs to be executed in parallel, e.g.: + +``` +jobs.run(method='dask') +``` + +The above example is just one way of using fsl-pipe - the library has several powerful features, including its own command-line interface, and the ability to skip jobs for output files that already exist. + + +<a class="anchor" id="fsl-sub"></a> +## fsl-sub + + +You can use the venerable `fsl_sub` to run several tasks in parallel both on your local machine, and on a HPC cluster, such as the ones available to us at FMRIB and the BDI. `fsl_sub` is typically called from the command-line, e.g.: + +> ``` +> for dataset in mydata/sub-*; do +> fsl_sub ./my_processing_script.py ${dataset} --jobram 16 +> done +> ``` + + +If you are working on a local machine, `fsl_sub` will block until your command has completed. You can run multiple commands in parallel by using "array tasks" - save each of the commands you want to run to a text file, e.g.: + +> ``` +> echo "./my_processing_script.py mydata/sub-01" > tasks.txt +> echo "./my_processing_script.py mydata/sub-02" >> tasks.txt +> echo "./my_processing_script.py mydata/sub-03" >> tasks.txt +> echo "./my_processing_script.py mydata/sub-04" >> tasks.txt +> echo "./my_processing_script.py mydata/sub-05" >> tasks.txt +> ``` + +And then run `fsl_sub -t tasks.txt` - each of your commands will be executed in parallel. If you are working on a cluster, `fsl_sub` will schedule all of the commands to be executed simultaneously. + +You can also call `fsl_sub` from Python by using functions from the `fslpy` library: + +> ``` +> from glob import glob +> from fsl.wrappers import fsl_sub +> +> for dataset in glob('mydata/sub-*'): +> fsl_sub(f'./my_processing_script.py ${dataset}', jobram=16) +> ``` + +And the `fslpy` wrapper functions allow you to run FSL commands with `fsl_sub`, and to specify job dependencies. For example, to submit a collection of jobs, you can pass `submit=True`: + +``` +from fsl.data.image import removeExt from fsl.wrappers import bet +from glob import glob + +for t1 in glob('braindata/??.nii.gz'): + t1 = removeExt(t1) + bet(t1, f'{t1}_brain', submit={'jobram':16}) +``` -from file_tree import FileTree -from fsl_pipe import pipe, In, Out -@pipe -def brain_extract(t1 : In, bet_output : Out, bet_mask : Out): - bet(t1, bet_output, mask=True) +You can also specify dependencies by using the ID of a previously submitted job, e.g.: + + +``` +from fsl.data.image import removeExt +from fsl.wrappers import robustfov, bet +from glob import glob -tree = FileTree.read('data.tree').update_glob('t1') -pipe.cli(tree) +for t1 in glob('braindata/??.nii.gz'): + t1 = removeExt(t1) + jid = robustfov(t1, f'{t1}_fov', submit=True) + bet(f'{t1}_fov', f'{t1}_brain', submit={'jobram':16, 'jobhold' : jid}) ```