Archive for April, 2009

April 3rd, 2009

The latest edition of the blog carnival, Math teachers at play, has been published over at Homeschool Bytes. There’s lots of great stuff to be found there from chessboard counting problems through to trachtenberg math.  Head on over and check it out.

Does anyone know what has happened with its sister carnival – the Carnival of maths?  I’ve not heard a thing about it since the last edition over a month ago.

April 2nd, 2009

I recently installed MATLAB 2009a on a Mac running Mac OS 10.5.6 and, although the installation seemed to go fine, MATLAB wouldn’t start.  The error message I received (copied from the console output) was


02/04/2009 16:19:42 [0x0-0x2d32d3].com.mathworks.StartMATLAB[36443] dyld: Library not loaded: /usr/X11R6/lib/libXmu.6.dylib
02/04/2009 16:19:42 [0x0-0x2d32d3].com.mathworks.StartMATLAB[36443] Referenced from: /Applications/MATLAB_R2009a.app/sys/os/maci/libXm.3.dylib
02/04/2009 16:19:42 [0x0-0x2d32d3].com.mathworks.StartMATLAB[36443] Reason: image not found

Now I don’t know very much about Macs and I tend to think of Mac OS X as a closed-source version of Linux with pretty bits so there may be a much better way of fixing this than what you are about to read but it did the job for me. Your mileage may vary.

Firing up a terminal I had a look to see if the offending file was anywhere on the machine by typing

locate libXmu.6.dylib

Sure enough I had it in /usr/X11/lib but MATLAB was looking for it in /usr/X11R6/lib so I created a symbolic link as follows

sudo ln -s /usr/X11 /usr/X11R6

Tried MATLAB again and it worked perfectly. Let me know if this works for you or if you are a Mac expert and you know of a better way.

April 1st, 2009

My brother sent me a link to the song below and I am loving it. You’ll need a smattering of undergraduate mathematics to get the jokes but if they sail cleanly over your head then start googling the terms. I’ve never seen a better motivation to learn group theory ;)

This is old,old news so I apologise to anyone who may have seen it before.

Update:  Wow!  These guys have produced a CD with this song on it.  Ordering now….(no I won’t get any comission if you do the same).

April 1st, 2009

This is part 1 of a series of articles devoted to demonstrating how to call the Numerical Algorithms Group (NAG) C library from Python. Click here for the index to this series.

Our first NAG/Python example is going to use the NAG function s13acc which calculates the Cosine integral Ci(x) defined as

Cosine Integral

According to the NAG documentation, the algorithm used is based on several Chebyshev expansions. So, let’s see what we need to do to access this function from Python.

Assuming that you have installed the cllux08dgl implementation of the NAG C library, you should find that the following Python code evaluates Ci(x) for x=0.2.

#!/usr/bin/env python
from ctypes import *

libnag = cdll.LoadLibrary("/opt/NAG/cllux08dgl/lib/libnagc_nag.so.8")
nag_cos_integral = libnag.s13acc
nag_cos_integral.restype=c_double

x = c_double(0.2)
ifail=c_int(0)

y= nag_cos_integral( x, ifail )
print "x= %s, cos_integral= %s" % (x.value,y)


Save (or download) this to a file called s13acc.py, make it executable and run it by typing the following at a bash prompt.

chmod +x ./s13acc.py
./s13acc.py

If all has gone well then you should get following result

x= 0.2, cos_integral= -1.04220559567

Since this our first piece of NAG/Python code let’s go through it line by line.

from ctypes import *

This simply imports everything from the standard ctypes module and makes it available in the global namespace.

libnag = cdll.LoadLibrary("/opt/NAG/cllux08dgl/lib/libnagc_nag.so.8")
nag_cos_integral = libnag.s13acc

The first line loads the NAG library using the cldll.LoadLibrary() function and associates it with an object I have named libnag whereas the second line pulls the function s13acc out of libnag and associates it with an object having the more user-friendly name of nag_cos_integral.

This is the least portable part of the code. If you are using a different implementation of the NAG C library then you will need to change the path in the LoadLibrary function.

nag_cos_integral.restype=c_double

The ctypes module provides us with a set of C compatible data-types such as c_int, c_double, c_char and so on, and we have to use these when we interact with C functions. The object nag_cos_integral represents the NAG C function we wish to call and by default ctypes assumes that the return type of all C functions is of type c_int unless we tell it otherwise.

We know from the documentation for s13acc that its return type is double and so here we are using the restype method function to set the return type of nag_cos_integral to c_double.

x = c_double(0.2)
ifail=c_int(0)

Here, we are setting up our input arguments. x is straightforward enough but the observant reader will notice that there is something fishy going on with the ifail parameter. The NAG documentation tells us that the ifail parameter of s13acc should be a pointer to a NagError structure but structures are a complication that I don’t want to deal with here so I have cheated and used the fact that the integer 0 is defined as NAGERR_DEFAULT via an enumeration in the C library header file. In short, this means that I don’t have to use a NagError structure if I don’t want to. Full details can be found in section 2.6 of the Essential Introduction to the NAG C Library.

We’ll look at how to use the NagError structure properly via Python in a later article for those who need it.

y= nag_cos_integral( x, ifail )

Here we pass our input parameters to the nag_cos_integral function and store the result in y. When I was working all of this out for the first time, I expected y to be of type c_double. After all, we earlier used restype to set the return type of nag_cos_integral to c_double so that’s what I expected to get but it turns out that y is a plain old python double. This is clearly explained in the ctypes documentation and I quote the relevant section below

‘Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. In other words, if a foreign function has a restype of c_char_p, you will always receive a Python string, not a c_char_p instance.’


print "x= %s, cos_integral= %s" % (x.value,y)

Finally, we actually print the output. Since x is a c_double we need to use the value attribute to ensure that 0.2 gets printed rather than c_double(0.2). The variable y is a python double as explained earlier so it needs no special treatment.

That’s it for this article in the series. Next time I’ll give an example using this function along with matplotlib to produce some more interesting output before moving onto callback functions.

As always, questions and comments are welcomed.

April 1st, 2009

The NAG library is possibly the most comprehensive numerical library available today with over 1500 functions and a long and distinguished history going back almost 40 years.  Although it is commercial, NAG is a not-for-profit company and has donated large amounts of code to the open source community over the years.  The library covers many application areas including special functions, optimization, curve fitting, statistics, numerical differentiation and linear algebra among others with even more coming up in the next release. It has been available in several different programming languages over the years but these days you can get it in essentially four flavours – The NAG Fortran Library, The NAG C Library, the Maple-NAG connector and the NAG Toolbox for MATLAB.

I have been supporting users of the NAG library at Manchester University for a few years now and one of the most common reactions I get from a potential user of the NAG libraries when they see the list of available languages is to say ‘I don’t program in any of those – I program in XYZ – so the NAG library is no use to me.’ where XYZ might be Java, Perl, Visual Basic, Python, R or one of any number of weird and wonderful possibilities.

It turns out that YOUR choice of language almost doesn’t matter as far as NAG is concerned since, with a bit of work, you can call the NAG routines from pretty much any language you care to mention. Put another way, NAG program in Fortran (and C) so you don’t have to. One language that has been mentioned a lot recently is Python.

Mat Cross, an employee of NAG, wrote a guide a little while ago giving detailed instructions on how to call the NAG Fortran library from Python using a module called F2PY and very nice it is too. However, some people are never happy and almost as soon as the article was published I started getting queries about the NAG C library and Python. As far as I could tell this particular combination hadn’t been covered by anyone before so I rolled up my sleeves to see what I could come up with.

After all, how hard could it be?

I have lost count of the number of times I have regretted uttering that particular phrase but in this case, thanks to a wonderful Python module called ctypes, the answer turns out to be ‘Not nearly as hard as you might expect’.

The results of my investigations will be posted on Walking Randomly over the next few weeks and will include several examples of how to use the NAG C library within Python. I’ll start off with the simplest of NAG functions and steadily move towards some of the most complex. On the way we will cover several areas of numerical mathematics including special functions, numerical quadrature, root finding and optimization.

I will initially be concentrating on Ubuntu Linux since that is my favourite development environment but I am aware that users of both NAG and Python make use of many platforms including Windows and Mac OS X. If there is sufficient interest then I will make other platform-specific articles available in the future.

The list below contains links to all of the articles published in the series so far and will be expanded as new ones come online so this post will eventually serve as an index to the whole series. Extra topics may be considered on request.

Topic List (will be expanded as new articles are available)

  1. Making simple NAG C functions available to Python
  2. Plotting the Cosine Integral using NAG and matplotlib
  3. Callback functions (The example code given is for finding the zero’s of an equation)
  4. Structures (The example code given is for Numerical Integration)
  5. Callback functions with communication (The example code solves a simple 1d minimization problem)
  6. PyNAG – A Python package for interfacing with the NAG C Library

Implementation specifics
The NAG C library is available for a wide range of platforms and C compilers (representing 26 different combinations when I last counted) but I only wanted to focus on one for the sake of sanity! In particular, I am using cllux08dgl throughout this series which is for 32bit Linux and was compiled using the gcc compiler.  I am using version 8.10 of Ubuntu Linux.

I imagine that most of what I write will be directly transferable, with minor modifications, to other versions of the NAG C library.  After all Python is quite portable but there may be some differences if you are using a platform wildly different from mine.  Where I am able, I will help people get the examples working on their platform of choice but reserve the right to refer you to the NAG support team if necessary.

Finally, I have developed all of this series using 2.5.2 and have no idea if it will work in later versions or not.