## Command line Mathematica on Mac OS X

February 27th, 2010

On a Linux machine with a normal install of Mathematica you can usually get access to a command line version of Mathematica by typing

math

at the command line.  Command line Mathematica is useful for situations where you want to do batch processing, perhaps as part of a Condor pool or something, but I’ll not write about that until another time.

On a Mac, however, a standard install of Mathematica doesn’t give you a math command so you have to create it yourself.  Add the following line to your system’s /etc/bashrc file.

alias math="/Applications/Mathematica.app/Contents/MacOS/MathKernel"

Now, when you type math at the command prompt it will behave just like a Linux system which is sometimes useful.

## Integrating Abs(x) with Mathematica

February 17th, 2010

Someone recently emailed me to say that they thought Mathematica sucked because it couldn’t integrate abs(x) where abs stands for absolute value.  The result he was expecting was

When you try to do this in Mathematica 7.0.1, it appears that it simply can’t do it. The command

Integrate[Abs[x], x]

just returns the integral unevaluated

I’ve come across this issue before and many people assume that Mathematica is just stupid…after all it appears that it can’t even do an integral expected of a high school student. Well, the issue is that Mathematica is not a high school student and it assumes that x is a complex variable. For complex x, this indefinite integral doesn’t have a solution!

So, let’s tell Mathematica that x is real

Integrate[Abs[x], x, Assumptions :> Element[x, Reals]]

which is Mathematica’s way of saying that the answer is -x^2/2 for x<=0 and x^2/2 otherwise, i.e. when x>0. It’s not quite in the form we were originally expecting but a moments thought should convince you that they are the same thing.

Interestingly, it seems that Wolfram Alpha guesses that you probably mean real x since it just evaluates the integral of abs(x) directly. It does, however, give the result in yet another form: in terms of the signum function, sgn(x):

A couple of weeks ago I am pretty sure that Wolfram Alpha gave exactly the same result as Mathematica 7.0.1 so I wonder if they have quietly upgraded the back-end Kernel of Wolfram Alpha.  Perhaps this is how Mathematica version 8 will evaluate this result?

## A little mathematics for Valentine’s day

February 10th, 2010

This is not a serious post but then mathematics doesn’t have to be serious all the time does it?  Ever wondered what the equation of a 3D heart looks like?  An old post of mine will help you find the answer using Mathematica.  Click on the image for more details (and a demonstration that you can run using the free Mathematica player).

I don’t save all of my love for Mathematica though. I’ve got some for MATLAB too:

%code to plot a heart shape in MATLAB
%set up mesh
n=100;
x=linspace(-3,3,n);
y=linspace(-3,3,n);
z=linspace(-3,3,n);
[X,Y,Z]=ndgrid(x,y,z);
%Compute function at every point in mesh
F=320 * ((-X.^2 .* Z.^3 -9.*Y.^2.*Z.^3/80) + (X.^2 + 9.* Y.^2/4 + Z.^2-1).^3);
%generate plot
isosurface(F,0)
view([-67.5 2]);


Did you know that the equation for a heart (or a cardioid if you want to get technical) is very similar to the equation for a flower?  The polar equation you need is  and you get a rotated cardioid for n=1.  Change n to 6 and you get a flower.  Let’s use the free maths package, SAGE, this time.

First, define the function:

def eqn(x,n):
return(1-sin(n*x))


then plot it for n=1

polar_plot(eqn(x,1), (x,-pi, pi),aspect_ratio=1,axes=False)


and for n=7

polar_plot(eqn(x,7), (x,-pi, pi),aspect_ratio=1,axes=False)


Back to Mathematica and the Wolfram Demonstrations project. We have a Valentine’s version of the traditional Tangram puzzle.

Feel free to let me know of any other Valentine’s math that you discover, puzzles, fractals or equations, it’s all good :)

Update Feb 14th 2011

Mariano Beguerisse Díaz sent me some MATLAB code that uses a variation on the standard mandelbrot and I turned it into the movie below.  His original code is in the comments section

## Free MATLAB toolboxes

February 9th, 2010

MATLAB is an extremely popular system in which to do computation of any kind.  In addition to the basic MATLAB package, The Mathworks sell dozens of add-on toolboxes for specialist (and not-so specialist) subject areas including curve fitting, statistics, bioinformatics, wavelet analysis, splines, optimisation, parallel computing and much more.  Although they are very good, these toolboxes can be rather expensive, especially if you find yourself needing several of them.

There are many free MATLAB toolboxes available which vary in quality from superb to complete trash and, obviously, you are only interested in the superb ones.  The following MATLAB toolboxes are all free and they are all very good – in every case I know at least one research group (who’s opinion I respect) that uses them extensively.

• Chebfun – The chebfun project is a collection of algorithms, and a software system in object-oriented MATLAB, which extends familiar powerful methods of numerical computation involving numbers to continuous or piecewise-continuous functions.
• IFISS Software Package – The IFISS software can be used to generate typical linear systems arising from finite element discretizations of steady and unsteady diffusion, convection-diffusion, Stokes flow and Navier-Stokes flow problems.
• NaN Toolbox for MATLAB and Octave –  A statistics and machine learning toolbox for MATLAB
• N-Way Toolbox for MATLAB – The N-way Toolbox for MATLAB  is a freely available collection of functions and algorithms for modelling multiway data sets by a range of multilinear models.
• MATLAB tensor toolbox – Tensors (also known as multidimensional arrays or N-way arrays) are used in a variety of applications ranging from chemometrics to psychometrics.
• NLEVP: A Collection of Nonlinear Eigenvalue Problems – This contains problems from models of real-life applications as well as problems constructed specifically to have particular properties.
• pMATLAB – A free parallel computing toolbox for MATLAB.  Check out the book here.
• Poblano toolbox for MATLAB – Poblano is a Matlab toolbox of large-scale algorithms for unconstrained nonlinear optimization problems.
• Statistical Parametric Mapping – The SPM software package has been designed for the analysis of brain imaging data sequences. The sequences can be a series of images from different cohorts, or time-series from the same subject.
• The Matrix Computation Toolbox – The Matrix Computation Toolbox is a collection of MATLAB M-files containing functions for constructing test matrices, computing matrix factorizations, visualizing matrices, and carrying out direct search optimization.
• The Matrix Function Toolbox – The Matrix Function Toolbox is a MATLAB toolbox connected with functions of matrices.
• Wavelab – A free wavelets toolbox from Stanford.

I’ll update this page whenever I come across other quality free toolboxes.  Feel free to point me to more in the comments section but please only do so if you have used the toolbox extensively and you are willing to talk to me about it via email.

Update (29th March 2010):Added the Poblano and Tensor toolboxes along with several from Manchester University.

## Fun with JavaFX on Ubuntu Linux

February 8th, 2010

A friend of mine got me interested in JavaFX recently and my interest grew when I discovered that it had some nice charting functionality.  Dean Iverson has written some great tutorials on the subject over at his blog and includes a link to a demo showing some of the different plot types that are available.

The demo is called ChartDemo and can be found here

http://pleasingsoftware.blogspot.com/2009/06/this-is-test.html

In an ideal world you simply have to click on the demo’s screenshot for it to download and launch but that wasn’t what happened for me.  What happened when I clicked on it was nothing.  No error messages…just nothing.  It’s difficult to google ‘nothing happened’ and get something useful so I downloaded the demo (which had the filename ChartDemo.jnlp) and tried to launch it from the command line using

javaws ChartDemo.jnlp

This gave me the error message

netx: Unexpected net.sourceforge.jnlp.ParseException: Invalid XML document syntax. at
net.sourceforge.jnlp.Parser.getRootNode(Parser.java:1200)

What follows is the story of how I eventually got this demo to work in the hope that it will help someone out there.

So, first things first, what are some of the relevant system specs I am using?  Well, I am running 32bit Ubuntu Linux 9.10 (Karmic Koala) and

java -version

gives

java version "1.6.0_0"
OpenJDK Runtime Environment (IcedTea6 1.6.1) (6b16-1.6.1-3ubuntu1)
OpenJDK Server VM (build 14.0-b16, mixed mode)

Now, when I googled the error message I discovered that Linux (more specifically, I guess, the OpenJDK) is much more sensitive to xml errors than Windows/Mac OS X (.jnlp files are written in xml).  Take double quotes for example; according to the W3C XML recommendations you should not use \” inside an xml attribute but should use “&quot;” instead.  Some java implementations don’t seem to care but, at the time of writing at least, OpenJDK definitely does.  Follow this link to see the original discussion thread where I learned this.

The practical upshot of this extra level of strictness is that .jnlp files that work just fine on Windows and Mac OS X won’t work on Linux and I guessed that was what as happening here.  Sadly there were no examples of \” in ChartDemo.jnlp for me to change to “&quot;” so there must be something else ‘wrong’ with it; but what?

I decided to try the ‘stare at it until you figure it out’ approach to debugging and left the laptop on the side of the sofa while watching a movie on TV.   About halfway through the movie, inspiration struck and I changed the line

<update check="background">

to

<update check="background"/>

which got things past the xml parsing stage. Sadly, I then hit another problem. Rather than a working ChartDemo, my efforts were rewarded with nothing more than just a blank window and a load of java errors in the terminal. When I say ‘a load’ I mean HUNDREDS and none of them looked particularly illuminating. I was starting to remember why I had avoided Java in the past but was not about to give up so easily.

Let’s take stock:

• The .nlbp file was fine (or at least didn’t return any parse errors)
• The ChartDemo code must be bug free because if it wasn’t then the author would have been told so rather quickly in the comments section of his blog
• My Java setup was presumably fine since I was able to run other JavaFX examples. For example I successfully worked through a JavaFX programming tutorial on Sun’s website without incident.

Of those three points I figured that the third one was the most likely to be wrong. It was OpenJDK’s handling of the .jnlp file that caused my first problem so maybe it was causing this second problem too. Could I switch from using OpenJDK to a different version of Java I wondered? Some googling ensued and I discovered some useful incantations.

I can list the versions of Java installed on my machine with the command

sudo update-java-alternatives -l

to get

java-6-openjdk 1061 /usr/lib/jvm/java-6-openjdk
java-6-sun 63 /usr/lib/jvm/java-6-sun

I can change from the openjdk to sun-java with

sudo update-java-alternatives -s java-6-sun

Once I did this I tried to run the ChartDemo.nlbp file again:

javaws ChartDemo.jnlp

and it worked perfectly. I was rewarded with a very nice demo of JavaFX’s charting functionality and Dean’s tutorials proved to be very useful to me. So useful in fact that I bought his book.

Incidentially, the java-6-sun version of java doesn’t care about the syntax of the .jnlp file quite so much as openjdk. However, if you want to change back to using openjdk you can do

sudo update-java-alternatives -s java-6-openjdk

I hope this little tale helps someone out there. Let me know if it does and also feel free to let me know if I have got anything wrong. My knowledge of all things Java is rather basic at the moment to say the least – something I am trying to change.

February 4th, 2010

• It’s just a big iPhone..without the ability to phone; which sucks. (Example)
• It doesn’t have flash so it sucks. (Example)
• It doesn’t multi-task so it sucks. (Example)
• Apple are evil because they take away control of how we use their devices.  So, the iPad sucks. (Example)
• The iPad is going to force ebook prices up.  This sucks. (Example)
• The iPad doesn’t have a camera.  This sucks too! (Example)
• The name sucks! (Example)

Now, before I go on, bear in mind that I am a card-carrying, fully paid up member of the Linux/Android community.  My phone is a HTC Hero running Android, my work desktop machine spends 95% of it’s time running Linux while my personal laptop runs it 100% of the time.  Bashing the likes of Apple and Microsoft has been a side-hobby of mine for years and has given me at least one thing in common with almost every computer geek I have ever met.  I would never buy a Mac, not in a million years,  and I am highly unlikely to ever switch from Android to iPhone.

Despite all of this, however, I decided that I would like to buy an iPad after watching just the first few minutes or so of Steve Job’s iPad presentation.  As soon as he announced the price I knew that I would be buying one…without hesitation.  Suddenly I regretted all of the Apple bashing I have done over the years as I knew full well that my friends and colleauges weren’t going to let me live this one down.  Oh yes…I am going to be in for a roasting over this particular purchase; a roasting that I will happily endure.  If you’re interested, I’ll tell you why.

The never-ending commute

I live in Sheffield but work in Manchester and I don’t drive a car.  The practical upshot of this is that I spend somewhere between 3 and 3.5 hours every day sitting on either a tram or a train.  What I do with this time varies a lot according to factors such as how tired I am, how much work I need to do, the availability of seats etc etc.  I always carry my Android phone and I almost always carry my laptop.  Depending on my mood you might also find me carrying books, a newspaper or two and maybe a DVD.

In general, if I am doing something serious, such as writing code or a document, then I’ll be using my laptop and if I am doing something frivolous, such as catching up on RSS feeds, playing games, listening to music, reading ebooks etc, then I’ll be using my Android phone.  Of course, there are exceptions to this rule, but they are….well, the exception.

A big screen, lots of apps, games, a decent e-book reader, tv-shows and movies

I love the Hero but I often wish it had a bigger screen – a MUCH bigger screen.  A screen about the size of the iPad would do nicely but then it would far too big to be a phone.  My laptop’s got a nice sized screen but it’s heavy and people think you are a crazy-man when you get your laptop out on the tram or bus.  So, if I want a big screen then I need another device and the iPad will do nicely.

I get bored easily and am always on the lookout for new apps or games to waste my commute time with.  I have an Android device to play with but I am missing out on all those Apple-exclusive apps that you can get for the iPhone OS.  I considered buying an iPod touch but couldn’t justify spending the money on one JUST to get access to iPhone apps.  The iPad offers me a bigger screen AND access to the Apple App store so it’s already ahead of the iPod touch for me.

I like playing video games and have to say that I am rather disappointed by the amount of games available for Android (It is getting better, however).  I’m not a hardcore gamer though, not by any stretch of the imagination.  Someone gave me a PSP a while ago but I can’t be bothered to carry it around, the games are too expensive and I keep losing the charger.  Mobile phone games are just right for me; they are cheap, easy to pick up and put down and the best ones are a lot of fun.  The iPhone has TONS of games for it and I’ll be able to play them all on the iPad.

Movies and TV shows on the train….at the moment I watch them on my laptop.  The iPad will be easier.

Finally, I’m hoping that the iPad will replace my need to carry a newspaper.  For it to do so I need an app for The Times that will look just like the dead-tree version.  It should also allow me to download the entire newspaper overnight and store it locally on the iPad.  A network only version would be no use at all because, although the commute through The Pennines is exceedingly beautiful, it is a 3G dead-zone most of the time.  I’ll happily pay a subscription to such a service as long as it’s cheaper than the dead-tree version of the paper.

Instant-on web-browsing, photos and a board-game platform

When I am at home I often find that I want to quickly go online to look something up, buy something or bash out a quick email.  If I use my laptop then I sometimes spend more time booting the thing up and down than it takes to do the task.  If I use my phone then the small screen and even smaller keyboard becomes an issue again.  The iPad would be perfect for this quick and casual kind of Internet surfing.  The lack of Flash support will be a pain but I won’t lose any sleep over it.

I like playing traditional board games.  You know….things such as Chess, Checkers, Scrabble and Backgammon and, ideally, I like to play against people rather than computers.  It occurred to me the other day that the iPad would be the perfect platform for board-games – simply as a replacement for the board and all of the pieces if nothing else.  It will never be as good as the hand crafted, wooden chess set that my wife bought for my birthday one year but it will serve as a great replacement for our magnetic games compendium next time we go on holiday.

Like many people these days, my wife and I have thousands of digital photographs and if we want to look through them we tend to use a laptop.  In the future I imagine we will use an iPad, simply because it will be quicker and easier to pass around.

Future possibilities…Wolfram Demonstrations?

When I first got my Android phone, I thought that it would be cool if Wolfram Research released an Android version of their free Mathematica Player to allow me to play with Wolfram Demonstrations on the move.  I quickly realised that this would be a dumb thing to do, on Android or iPhone, because phone screens are too small.  The iPad screen isn’t too small though!  Wolfram could make maths VERY hands-on.  How about it Wolfram?

The price

\$499 dollars for the entry level version.  That’s about 315 pounds at the current exchange rate.  In a year, I spend more than that on coffee and it’s not particularly good coffee either.  At this price point, if my iPad purchase proves to be a disaster then I just won’t care (too much) – I’ll just drink less coffee for a while and give the iPad away.  Alternatively I’ll just use it to put my coffee mugs on.

• The lack of Flash. If I NEED to browse a Flash based website then I’ll just use my laptop, or my Hero.
• 3G.  I’ll be using the iPad on my commute most of the time.  3G coverage SUCKS on my particular train route.  If I desperately need a net connection RIGHT NOW then I’ll fall back to my phone.  So, I’ll buy the wifi-only version.  Having wifi was enough back in my Dell Axim days.
• Lack of multi tasking. When I am messing around, you know…just wasting time, I only need to do one thing at a time.  Read one book, play one game, watch one movie.
• Lack of control over my computing experience. When I care about having full control over my system, I’ll use Linux or Android.  For the stuff I plan on using the iPad for, I just don’t care.
• The price of ebooks. If they are too expensive then I won’t buy them.  When it makes more sense to buy the dead-tree version then I will.
• DRM. There are lots of DRM-free outlets for stuff these days.  If I think that a DRM version of something will affect me in any way then I won’t buy it.  Other times I just won’t care.  Who cares if my newspaper has DRM on it?  I’ll be throwing it away the instant I’ve finished with it anyway.  The same goes for a lot of paperback fiction and episodes of TV shows.  My music, movies and textbooks, on the other hand, I care more about.  I’ll continue to get my music from Amazon, my movies on DVD and my textbooks will be dead-tree if they aren’t DRM free.
• Lack of camera. I’ve got a webcam on my laptop, I’ve got a 10 megapixel point and shoot camera and I’ve got a half decent camera on my phone.  If the iPad had one then yay! but it hasn’t and I don’t need one.
• The name. Who cares what something is called?
• No removable storage. The basic iPad model has 16Gb which will be enough.  My phone has removable storage in the form of a micro SD card.  It’s 2Gb and isn’t full.
• It’s not Android. Some of my friends say I should wait until there is a good Android tablet and buy that instead.  I don’t want to.  I’ve got Android on my phone and I like it but I want something a bit different.
• The backlash from my friends. Bring it :)

Drip,Drip,Drip,Drip…want one!

Taken individually, none of the reasons I’ve given in this article are compelling enough to make me go out and buy an iPad – or any other device for that matter.  It’s the steady accumulation of reasons that slowly but surely make the iPad into something that I want.  The plain fact of the matter is that I don’t need one – I just want one.  The iPad won’t change my life, it’ll just make it very slightly better in a number of  small and rather trivial ways – very much like my old Dell Axim x50v PDA did a few years ago.  It’s about the same price as the Axim was too.

For me, the iPad is for trivial computing…it’s for stuff that I could do elsewhere but just can’t be bothered because of screen size, boot up time, price…whatever.  It’s not a phone replacement, it’s not a laptop replacement, it sure as hell isn’t a Desktop replacement and I don’t want it to be any of these things.  It’s cheap, different and could fill lots of little gaps in my digital life.  Since I’ll only be using it for trivial stuff, I simply don’t care about the things that it hasn’t got or can’t do because I can do all of those on my other devices anyway.

Yep..I want an iPad and, although I never really knew it, I always have.