Tag Archives: productivity tools

Run, Python, run! Part 1: Timing your code

Sooner or later everyone comes to a realisation that one’s code is slow, too slow. Thankfully there were a lot of ‘everyone’ before us and they actually did something about it. This means that the tempting option of leaving one’s laptop churning the simulation and going on a month long holiday is not longer defendable. This blogpost will sketch out what one can do instead. It draws from my own experience, so it’s very mac-centric (windows users can just skip all the paragraphs on how to deal with the hell that apple sends your way) and applies to scripts written in Python only. For a tutorial on how to profile your code in NetLogo, check out Colin Wren’s post here.

Also, if you’re a proper software developer stop reading now or you may get a cardiac arrest with my frivolous attitude to the comp science nomenclature. Having wasted hours on deciphering the cryptic jargon of online tutorials, stack overflow and various bits of documentation I make no apologies.

Finally, a piece of warning: it may take up to a full day to set everything up. There will be cursing, there will be plenty of ‘are you kidding me’ and ‘oh c’mon why cannot you just work’ moments, so make sure you take frequent breaks, switch the computer off and on from time to time and know that perseverance is key. Good luck!

The basics

The key to speeding up your code is to a) figure out which bits are actually slow and b) make them go faster. The first task is called ‘profiling,’ the second ‘optimisation’ (so that you know what to google for). This post will be about profiling with another one on optimisation following soon.

A good place to start is to check how long your code takes to run overall. You can time it by typing in the terminal on Mac/command line in Windows (don’t type the ‘$’ it’s just a marker to say ‘new line’):

$ time python script_name.py  

where script_name.py is the name of your file. Remember to either navigate to the folder containing the file by typing cd (meaning ‘change directory’) followed by the path to the file, eg. cd user/phd/python_scripts or provide the full path, e.g.

$ time python user/phd/p_scripts/script_name.py

If you cannot figure out what is the full path  (thank you apple, you really couldn’t make it any more complicated), drag and drop the file onto the terminal as if you were moving it from one folder to another and the full path will appear in a new line.

Screen Shot 2015-02-27 at 11.42.05

Once it works, the time function produces a pretty straight forward output, to tell you how long it all took:

real 0m3.213s
user 0m0.486s
sys 0m0.127s

Now, add up the sys and user times – if it is much less than the real time then the main problem is that you computer is busy with other stuff and the code needed to wait until other tasks were completed. Yep, switching your Facebook off may actually speed up the code. Sad times.

Profiling the functions

So far so good, but the overall time tells you little about which bit of the code is slowing things down. For the rescue comes the armada of profiling tools. The first step into the world of profiling is to watch this highly enjoyable talk: Python profiling. The first half is really useful, the second half is for some hardcore business application so you can skip it.

To sum it up, Python has a standard inbuilt tool called cProfile. You call it from the terminal  with:

 $ python -m cProfile script_name.py

And usually it produces pages upon pages of not particularly useful output, along the lines of:

163884 function calls (161237 primitive calls) in 5.938 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1    0.000    0.000    0.000    0.000 <string>:1(<module>)
1    0.000    0.000    0.000    0.000 <string>:1(ArgInfo)
1    0.000    0.000    0.000    0.000 <string>:1(ArgSpec)
1    0.000    0.000    0.000    0.000 <string>:1(Arguments)
1    0.000    0.000    0.000    0.000 <string>:1(Attribute)
1    0.000    0.000    0.000    0.000 <string>:1(DecimalTuple)
1    0.000    0.000    0.000    0.000 <string>:1(Match)
1    0.000    0.000    0.000    0.000 <string>:1(Mismatch)
1    0.000    0.000    0.000    0.000 <string>:1(ModuleInfo)
1    0.000    0.000    0.000    0.000 <string>:1(ParseResult)
1    0.000    0.000    0.000    0.000 <string>:1(SplitResult)

One needs to use some tools to trawl through this. To start with, it makes sense to stop viewing it in the the terminal window. If you run this command:

$ python -m cProfile -o script_output script_name.py

it will create a file with the data and  ‘script_output’ is the name you want to assign to that file. To then see the data in a browser window install the cprofilev tool.  As usual they tell you that one line of code:

$ pip install cprofilev 

in your terminal is enough to install it. Yeah, right, as if that was ever to happen. To start with, make sure you’ve got the words sudo and pip at the beginning of the line. Using sudo means that you’re pretending to be the root administrator, i.e. the almighty ‘this is my bloody computer and if I want to I will break it’ – you can also give yourself the root admin rights by following these instructions, but apple will drag you through pages and pages of warnings that will leave only the bravest of us actually daring to continue. So whenever I get an ‘access denied’ message I stick the sudo command in front  and usually it does the trick:

$ sudo pip install cprofilev 

If the terminal spits out an error message about pip, it is likely that you don’t have it installed, so type in the terminal :

$ sudo easy_install pip 

and try again. This should be enough of sweat to make it work but if it keep on producing error messages, go to the ultimate authority of google.  If it did work (i.e. you run the  $ sudo pip install cprofilev and it didn’t show any errors) type in the terminal:

$ cprofilev /path/to/script_output

script_output is the name you assigned to the file created with the cProfiler four code-snippets ago (scroll up). The terminal will spit out this fantastically cryptic message:

cprofilev server listening on port 4000

This just means that you need to copy past this line into your browser (Safari, Firefox, IE):


and the data will appear as a nice webpage where you can click on the headings and sort it by the number of calls, total time they took etc. You can find a comprehensive description of how to use it here.

Run, snake, run!

A more fancy way of doing it is to use the ‘Run Snake Run‘ tool. You can try to instal it from these files. Or from the terminal:

$ sudo easy_install SquareMap RunSnakeRun

You need wxPython to run the tool, thankfully this one has actually a ‘click’ installation type (I almost forgot these exists!): you can get the file from here. If may get an error saying that the disc is damaged, it’s not. It’s (yet again…) apple who does not want you to instal anything that is not ‘certified’ by them. Here are instructions on how to bypass it in the Mac internal settings.

If you’re a happy windows or linux user you’re good to go, if you have a mac there is one more bug, you probably get this error message:

OSError( """Unable to determine user's application-data directory""" )

This is because the software is not fully compatible with Mac OS X but you can repair it by typing in the terminal:

$ mkdir~/.config

Now, run this in your terminal:

$ runsnake script_output

where the script_output is that file you created with cProfiler, remember? The one you got with this line:

$ python -m cProfile -o script_output script_name.py

and you should now be able to get a nice visualisation of how much time each function consumes. It looks like this:

Screen Shot 2015-02-26 at 15.41.52

In the left hand side panel you can sort the functions by the execution time, the number of calls the combined time they took etc, while the right hand side panel shows the same information in a more human friendly format, i.e. in colour.

Line profiling

Run, snake, run is truly a fantastic tool and it gives you an idea of what eats the time and power pointing to the functions that may be optimised for a better performance. But, it also floods you with loads of the ‘inner guts of Python’ – functions inside functions inside functions hence finding out which bit of your code, i.e. the exact line, is the root of the problem is far from obvious. The line_profiler tool is great for that. There are some nice tutorial on how to use it here and here. To instal it try typing in the terminal:

$ sudo pip install line_profiler

This should do the trick, if not download the files from here and try all possible installation routes described here. Once it’s installed, in order to use it add the  @profile decorator in front of the function you want to test, for example:

Screen Shot 2015-02-26 at 16.30.37

and run from the terminal:

$ kernprof.py -l -v script_name.py

The -l flag makes the decorator (@profile) works and the -v flag is used to display the time when the script is finished.

If it doesn’t work make sure that you have the  kernprof.py in the same folder as the script you want to run (it’s in the line_profiler folder, you’ve downloaded earlier), or provide the full path to where it lives in your computer, for example:

$ /line_profiler-1.0/kernprof.py -l -v script_name.py

The output is pure joy and simplicity, and looks something like this:

Screen Shot 2015-02-26 at 16.35.03

Now, we’re talking. It clearly shows that in case of my script almost 60% of the time is spent on line 20 where I count how often each number appears in my list. If you need someone to spell out how to read the output, head to this tutorial.

If you want to go further, check out this tutorial on profiling how much memory the program uses and checking if none of it is leaking. Or get on with it and switch to working on speeding up the slow bits of your code. The next tutorial will give you a few hints on how to achieve it.

Top image source: Alan Cleaver on Flickr flickr.com/photos/alancleaver/2661425133/in/album-72157606825074174/

Starting with Python

No matter if you are an experienced NetLogo coder or have just started with modelling, learning how to code in a scripting language is likely to help you at some point when building a simulation. We have already discussed at length the pros and cons of using NetLogo versus other programming languages, but this is not a marriage, you can actually use both! There are certain aspects in which NetLogo beats any other platform (simplicity, fast development of models and many more), while in some situations it is just so much easier to use simple scripts (dealing with GIS, batch editing of files etc). Therefore, we’ve put together a quick guide on how to start with Python pointing out all the useful resources out there.

How to instal Python

It will take time, a lot of effort and nerves to install Python from scratch. Instead, go for one of the scientific distributions:

Anaconda is a free distribution containing all the useful packages, You can get it from here, and then simply follow the installation instructions here.

Enthought Canopy comes free for academic users. You can get it from here and there is a large training suite attached to it (https://training.enthought.com/courses).

The very first steps

There’s a beginner Python Coursera module starting very soon: https://www.coursera.org/course/pythonlearn but if you missed it, don’t worry, they repeat regularly.

Source: http://www.greenteapress.com/thinkpython/think_python_comp2.medium.png

If you prefer to work with written text, go for ‘Think Python‘ – probably the best programming textbook ever created. You can get the pdf for free, here. It is likely to take a week of full time work to get through the book and do all the exercises but it is worth doing it in one go. It’s unbelievable how quickly one forgets  stuff and then gets lost in further chapters. There are loads of other books that can help you to learn Python: with the Head First Python you could teach a monkey to code but I found it so slow it was actually frustrating.

Source: http://www.cengage.com/covers/imageServlet?epi=1200064128513708027464865671616351030

Alternatively, Python Programming for the absolute beginner is a fun one, as you learn to code by building computer games (the downside is I spent way too much time playing them). Finally, if you need some more practice, especially in more heavy-weight scientific computing I recommend doing some of the exercises from this course, and checking out Hans Fangohr’s textbook. There are many more beginner’s resources, you will find a comprehensive list of them here.

It is common that one gets stuck with a piece of code that just do not want to work. For a quick reference, the Python documentation is actually pretty clearly written and has examples.  Finally, StackOverflow is where you find help in more difficult situations. It’s a question-and-answer forum, but before you actually ask a question, check first if someone hasn’t done it already (in about 99% of cases they did). There is no shame in googling ‘how to index an array in python’, everyone does it and it saves a lot of time.

How to get from the for-loop into agents

There is a gigantic conceptual chasm every modeller needs to jump over: going from the simple to the complex. Once you learnt the basics, such as the for-loops, list comprehension, reading and writing files etc. it is hard to imagine how a complex simulation can be built from such simple blocks.

Source: http://www.greenteapress.com/compmod/think_complexity_cover.png

If you’re feeling suicidal you could try to build one from scratch. However,  there are easier ways. To start with, the fantastic ‘Think Python’ has a sequel! It’s called ‘Think Complexity’ and, again, you can get the pdf for free, here. This is a great resource, giving you a thorough tour of complexity science applications and the exercises will give you enough coding experience to build your own models.

The second way is to build up on already existing models (btw, this is not cheating, this is how most of computer science works).  There is a fantastic library of simulations written in Python  called PYCX (Python-based CompleX systems simulations). It contains sample codes of complex systems simulations written in plain Python. Similarly the OpenABM repository has at least some models written in Python.

And once you see it can be done, there’s nothing there to stop you!

Going further – Python productivity tools

There are several tools which make working in Python much easier (they all come with the  Anaconda and Enthought distributions).

Source: http://matplotlib.org/mpl_examples/api/logo2.hires.png

Visualisations: Matplotlib is the standard Python library for graphs. I am yet to find its limits and it is surprisingly easy to use. Another useful resource is the colour brewer.  It’s a simple website that gives you different colour palettes  to represent different type of data (in hex, rgb and cmyk so ready to be plugged into your visualisations straight away). It can save you a lot of time otherwise wasted on trying to decide if the orange goes ok with the blue…

The Debugger: The generic python debugger is called ‘pdb’ and you can find a great tutorial on how to use it here. I personally prefer the ipdb debugger, if only because it actually prints stuff in colour (you appreciate it after a few hours of staring at the code); it works exactly the same as the pdb debugger.

The IPython Notebook: The IPython notebook is a fantastic platform for developing code interactively and then sharing it with other people (you can find the official tutorial here). Its merits may not be immediately obvious but after a while there’s almost no coming back.

Sumatra: Sooner or later everyone experiences the problem of ‘which version of the code produced the results???‘. Thankfully there is a solution to it and it’s called Sumatra. It automatically tracks different versions of the code and links the output files to them.

Data Analysis: You can do data analysis straight in Python but there are tools that make it easier.

Source: http://pandas.pydata.org/_static/pandas_logo.png

I haven’t actually used Pandas myself yet, but it’s the talk of the town at the moment so probably worth checking out.

GIS: Python is the language of choice for GIS, hence the simple integration. If you are using ESRI ArcMap, create your algorithm in the model builder, go to -> export -> to python (see a simple tutorial here, and a more comprehensive one on how to use model builder and python here). You can do pretty much the same thing in QGIS (check out their tutorial, here). On top of that, you can use Python straight from the console (see a tutorial here).