Archive for the ‘sage interactions’ Category

December 27th, 2009

Regular readers of Walking Randomly will know that I am a big fan of the Manipulate function in Mathematica.  Manipulate allows you to easily create interactive mathematical demonstrations for teaching, research or just plain fun and is the basis of the incredibly popular Wolfram Demonstrations Project.

Sage, probably the best open source mathematics software available right now, has a similar function called interact and I have been playing with it a bit recently (see here and here) along with some other math bloggers.  The Sage team have done a fantastic job with the interact function but it is missing a major piece of functionality in my humble opinion – a Locator control.

In Mathematica the default control for Manipulate is a slider:

Manipulate[Plot[Sin[n x], {x, -Pi, Pi}], {n, 1, 10}]

Manipulate Sine

The slider is also the default control for Sage’s interact:

@interact
def _(n=(1,10)):
    plt=plot(sin(n*x),(x,-pi,pi))
    show(plt)

Interact Sine

Both systems allow the user to use other controls such as text boxes, checkboxes and dropdown menus but Mathematica has a control called a Locator that Sage is missing.  Locator controls allow you to directly interact with a plot or graphic.  For example, the following Mathematica code (taken from its help system) draws a polygon and allows the user to click and drag the control points to change its shape.

Manipulate[Graphics[Polygon[pts], PlotRange -> 1],
 {{pts, {{0, 0}, {.5, 0}, {0, .5}}}, Locator}]

Mathematica Locator Example

The Locator control has several useful options that allow you to customise your demonstration even further. For example, perhaps you want to allow the user to move the vertices of the polygon but you don’t want them to be able to actually see the control points. No problem, just add Appearance -> None to your code and you’ll get what you want.

Manipulate[Graphics[Polygon[pts], PlotRange -> 1],
 {{pts, {{0, 0}, {.5, 0}, {0, .5}}}, Locator, Appearance -> None}]

Another useful option is LocatorAutoCreate -> True which allows the user to create extra control points by holding down CTRL and ALT (or just ALT – it depends on your system it seems) as they click in the active area.

Manipulate[Graphics[Polygon[pts], PlotRange -> 1],
 {{pts, {{0, 0}, {.5, 0}, {0, .5}}}, Locator,
  LocatorAutoCreate -> True}]

When you add all of this functionality together you can do some very cool stuff with just a few lines of code. Theodore Gray’s curve fitting code on the Wolfram Demonstrations project is a perfect example.

All of these features are demonstrated in the video below

So, onto the bounty hunt.  I am offering 25 pounds worth (about 40 American Dollars) of books from Amazon to anyone who writes the code to implement a Locator control for Sage’s interact function.  To get the prize your code must fulfil the following spec

  • Your code must be accepted into the Sage codebase and become part of the standard install.  This should ensure that it is of reasonable quality.
  • There should be an option like Mathematica’s LocatorAutoCreate -> True to allow the user to create new locator points interactively by Alt-clicking (or via some other suitable method).
  • There should be an option to alter the appearance of the Locator control (e.g. equivalent to Mathematica’s Appearance -> x option).  As a minimum you should be able to do something like Appearance->None
  • You should provide demonstration code that implements everything shown in the video above.
  • I have to be happy with it!

And the details of the prize:

  • I only have one prize – 25 pounds worth of books (about 40 American dollars) from Amazon.  If more than one person claims it then the prize will be split.
  • The 25 pounds includes whatever it will cost for postage and packing.
  • I won’t send you the voucher – I will send you the books of your choice as a ‘gift’.  This will mean that you’ll have to send me your postal address. Don’t enter if this bothers you for some reason.
  • I expect you to be sensible regarding the exact value of the prize.  So if your books come to 24.50 then we’ll call it even.  Similarly if they come to 25.50 then I won’t argue.
  • I am not doing this on behalf of any organisation.  It’s my personal money.
  • My decision is final and I can withdraw this prize offer at any time without explanation.  I hope you realise that I am just covering my back by saying this – I have every intention of giving the prize but whenever money is involved one always worries about the possibility of being ripped off.

Good luck!

Update (29th December 2009): The bounty hunt has only been going for a few days and the bounty has already doubled to 50 pounds which is around 80 American dollars.  Thanks to David Jones for his generosity.

December 10th, 2009

There have been a couple of blog posts recently that have focused on creating interactive demonstrations for the discrete logistic equation – a highly simplified model of population growth that is often used as an example of how chaotic solutions can arise in simple systems.  The first blog post over at Division by Zero used the free GeoGebra package to create the demonstration and a follow up post over at MathRecreation used a proprietary package called Fathom (which I have to confess I have never heard of – drop me a line if you have used it and like it).  Finally, there is also a Mathematica demonstration of the discrete logistic equation over at the Wolfram Demonstrations project.

I figured that one more demonstration wouldn’t hurt so I coded it up in SAGE – a free open source mathematical package that has a level of power on par with Mathematica or MATLAB.  Here’s the code (click here if you’d prefer to download it as a file).

def newpop(m,prevpop):
    return m*prevpop*(1-prevpop)

def populationhistory(startpop,m,length):
    history = [startpop]
    for i in range(length):
        history.append( newpop(m,history[i]) )
    return history

@interact
def _( m=slider(0.05,5,0.05,default=1.75,label='Malthus Factor') ):
    myplot=list_plot( populationhistory(0.1,m,20) ,plotjoined=True,marker='o',ymin=0,ymax=1)
    myplot.show()

Here’s a screenshot for a Malthus Factor of 1.75

Discrete Logistic Equation

and here’s one for a Malthus Factor of 3.1

Discrete Logistic Equation

There are now so many different ways to easily make interactive mathematical demonstrations that there really is no excuse not to use them.

Update (11th December 2009)

As Harald Schilly points out, you can make a nice fractal out of this by plotting the limit points.  My blogging software ruined his code when he placed it in the comments section so I reproduce it here (but he’s also uploaded it to sagenb)

var('x malthus')
step(x,malthus) = malthus * x * (1-x)
stepfast = fast_callable(step, vars=[x, malthus], domain=RDF)

def logistic(m, step):
   # filter cycles
   v = .5
   for i in range(100):
       v = stepfast(v,m)
   points = []
   for i in range(100):
       v = stepfast(v,m)
       points.append((m+step*random(),v))
   return points
points=[]
step = 0.005
for m in sxrange(2.5,4,step):
   points += logistic(m, step)
point(points,pointsize=1).show(dpi=150)

Logistic3

November 17th, 2009

Earlier today I was chatting to a lecturer over coffee about various mathematical packages that he might use for an upcoming Masters course  (note – offer me food or drink and I’m happy to talk about pretty much anything). He was mainly interested in Mathematica and so we spent most of our time discussing that but it is part of my job to make sure that he considers all of the alternatives – both commercial and open source. The course he was planning on running (which I’ll keep to myself out of respect for his confidentiality) was definitely a good fit for Mathematica but I felt that SAGE might suite him nicely as well.

“Does it have nice, interactive functionality like Mathematica’s Manipulate function?” he asked

Oh yes! Here is a toy example that I coded up in about the same amount of time that it took to write the introductory paragraph above (but hopefully it has no mistakes). With just a bit of effort pretty much anyone can make fully interactive mathematical demonstrations using completely free software. For more examples of SAGE’s interactive functionality check out their wiki.

Interactive Fourier Series

Here’s the code:

def ftermSquare(n):
 return(1/n*sin(n*x*pi/3))

def ftermSawtooth(n):
 return(1/n*sin(n*x*pi/3))

def ftermParabola(n):
 return((-1)^n/n^2 * cos(n*x))

def fseriesSquare(n):
 return(4/pi*sum(ftermSquare(i) for i in range (1,2*n,2)))

def fseriesSawtooth(n):
 return(1/2-1/pi*sum(ftermSawtooth(i) for i in range (1,n)))

def fseriesParabola(n):
 return(pi^2/3 + 4*sum(ftermParabola(i) for i in range(1,n)))

@interact
def plotFourier(n=slider(1, 30,1,10,'Number of terms')
,plotpoints=('Value of plot_points',[100,500,1000]),Function=['Saw Tooth','Square Wave','Periodic Parabola']):
    if Function=='Saw Tooth':
     show(plot(fseriesSawtooth(n),x,-6,6,plot_points=plotpoints))
    if Function=='Square Wave':
     show(plot(fseriesSquare(n),x,-6,6,plot_points=plotpoints))
    if Function=='Periodic Parabola':
     show(plot(fseriesParabola(n),x,-6,6,plot_points=plotpoints))
July 13th, 2009

My favourite free mathematics package has seen yet another relase. Released back on Thursday June 9th, version 4.1 of SAGE Math includes a nice array of new features, speed-ups and bug-fixes. Head over to the version 4.1 release tour for more details.

One of the things that I like about each new release of SAGE is that there is always something for everyone – no matter what their level of mathematics. For example, release 4.1 includes advanced functionality for constructing elliptic curves and also adds support for constructing irreducible representations of the symmetric group. On the other hand it also includes some new Sudoku solvers, faster integer division and improved histograms.

SAGE screenshot

If you are a user of SAGE then feel free to say hi in the comments section and let me know what you use it for.

June 9th, 2009

While catching up on all of the news I missed while on Vacation, I discovered that the world’s best open-source Maths package saw a new release at the end of May.  I haven’t had chance to download it yet but the breadth and depth of new features is astonishing.  Check out the comprehensive feature-tour here (note to commercial software developers I have bugged in the past – when I say that I’d like a detailed change-log for your latest release, this is the kind if thing I mean).

Scanning through the changes I note that they have dropped Maxima for core symbolic manipulation in favour of a package called Pynac.   Apparently, one practical upshot of this is that finding the determinant of symbolic matrices can be up to 2500 times faster!  very impressive.  I wonder how this change will affect symbolic calculus (if at all).

Unfortunately,  it looks like a full, native Windows version is still some way off which is a shame because one of my jobs this month is to prepare a load of maths applications for deployment on my University’s teaching clusters which run Windows.  Putting SAGE next to Mathematica, MATLAB and Mathcad would have been cool and a great way to encourage undergraduate users at Manchester University to try out the software.

Finally, some eye candy shamelessly stolen from the SAGE website.  The plot below demonstrates the new implicit_plot3d function.

SAGE implicit plot

May 15th, 2009

SAGE math is probably the best open-source maths package out there at the moment and slowly but surely I have been learning some of its tricks.  Combining 2D Plots is particularly easy for example.  Let’s plot a cosine curve in red

p1=plot(cos(x),x,-6,6,rgbcolor='red')
show(p1)

Cosine curve plotted with SAGE math

Now let’s plot a sine curve in green

p2=plot(sin(x),x,-6,6,rgbcolor='green')
show(p2)

Sine curve plotted with SAGE math

Combining these two plots into one single plot is extremely intuitive – just add them together

show(p1+p2)

Combined Sine/Cosine curves plotted with SAGE math

You don’t get much easier than that.  Powerful, easy to use and free – loving it!

April 27th, 2009

The latest version of the powerful free, open-source maths package, SAGE, was released last week.  Version 3.4.1 brings us a lot of new functionality compared to 3.4 and the SAGE team have prepared a detailed document showing us why the upgrade is worthwhile.

For example, the new complex_plot function looks fantastic.  From the documentation:

The function complex_plot() takes a complex function f(z) of one variable and plots output of the function over the specified xrange and yrange. The magnitude of the output is indicated by the brightness (with zero being black and infinity being white), while the argument is represented by the hue with red being positive real and increasing through orange, yellow, etc. as the argument increases.

sage: f(z) = z^5 + z - 1 + 1/z
sage: complex_plot(f, (-3, 3), (-3, 3))

Plot of a function of a complex variable in SAGE

Sage aims to become a ‘viable free open source alternative to Magma, Maple, Mathematica and Matlab’ and I think it is well on the way.  I become a little more impressed with it with every release and I am a hardcore Mathematica and MATLAB fan.

One major problem with it (IMHO at least) is that there is no native windows version which prevents a lot of casual users from trying it out.  Although you can get it working on Windows, it is far from ideal because you have to run a virtual machine image using VMWare player.  The hard-core techno geeks among you might well be thinking ‘So what?  Sounds easy enough.’ but it’s an extra level of complexity that casual users simply do not want to have to concern themselves with.  Of course there is also the issue of performance – emulating an entire machine to run a single application is hardly a good use of compute resources.

There is a good reason why SAGE doesn’t have a proper Windows version yet – it’s based upon a lot of component parts that don’t have Windows versions and someone has to port each and every one of them.  It’s going to be a lot of work but I think it will be worth it.

When the SAGE development team release a native Windows version of their software then I have no doubt that it will make a significant impact on the mathematical software scene – especially in education.  There will be nothing preventing every school and university in the world from having access to a world-class computer algebra system.

In an ideal world everyone would be running Linux but we don’t live in an ideal world so a Windows version of SAGE would be a step in the right direction.

Update: It turns out that a Windows port is being developed and something should be ready soon - http://windows.sagemath.org/ Thanks to mvngu in the comments section for pointing this out. I should have done my research better!

December 12th, 2008

David Joyner of the SAGE development team has come up with a couple of very nice mathematical Christmas greetings using a combination of SAGE (For the mathematics used to generate the images) and GIMP and Inkscape (for the text).  The first one is based on a Barnsley Fractal and the sage source code is available here.

small fern

David’s other creation is a Sierpinski gasket that has been coloured such that it resembles a Christmas tree.  The SAGE source code is given below.

gasket


def sierpinski_seasons_greetings():
"""
Code by Marshall Hampton.
Colors by David Joyner.
General depth by Rob Beezer.
Copyright Marshall Hampton 2008, licensed
creative commons, attribution share-alike.
"""
depth = 7
nsq = RR(3^(1/2))/2.0
tlist_old = [[[-1/2.0,0.0],[1/2.0,0.0],[0.0,nsq]]]
tlist_new = [x for x in tlist_old]
for ind in range(depth):
for tri in tlist_old:
for p in tri:
new_tri = [[(p[0]+x[0])/2.0, (p[1]+x[1])/2.0] for x in tri]
tlist_new.append(new_tri)
tlist_old = [x for x in tlist_new]
T = tlist_old
N = 4^depth
N1 = N - 3^depth
q1 = sum([line(T[i]+[T[i][0]], rgbcolor = (0,1,0)) for i in range(N1)])
q2 = sum([line(T[i]+[T[i][0]], rgbcolor = (1,0,0)) for i in range(N1,N)])
show(q2+q1, figsize = [6,6*nsq], axes = False)

It just goes to show that advanced mathematical software such as SAGE doesn’t just have to be used for teaching and research – it can be used for making mathematical Christmas cards too! SAGE is completely free and is available from the SAGE math website. Thanks to David for his work on this one.

November 30th, 2008

I have just installed SAGE 3.2 on my Ubuntu 8.10 machine and received the following error message.

It looks like jsMath failed to set up properly (error code -7). I will try to keep going, but it could get ugly.

I discovered a forum thread that suggested that installing jsmath-fonts would fix the problem

apt-get install jsmath-fonts

but, unfortunately, it didn’t. I found that I also had to install ttf-jsmath

apt-get install ttf-jsmath

A quick restart of firefox later and SAGE looked very pretty indeed!

May 12th, 2008

Regular readers of this blog will know that I have been keeping an eye on the open source mathematics package, SAGE, but have never really had time to take a closer look at it. A couple of things happened recently that made me find time to sit down and have a play with this extremely promising piece of software.

First of all I discovered that the developers of SAGE have been implementing a command called interact which is essentially a free version of the Mathematica command Manipulate. I love tinkering with Manipulate and so this open source alternative proved to be very tempting. Secondly, the developers of Sage recently released version 3.0 and, usually, a .0 release signifies a major milestone in development.

So first things first. What exactly is SAGE? In my opinion, the easiest way to sum up the answer to this question is to quote the projects mission statement which is

“Creating a viable free open source alternative to Magma, Maple, Mathematica, and Matlab.

No small task! I have access to three of the four CAS systems that SAGE has chosen to compare itself with and they are all extremely powerful (not to mention expensive) applications backed by large, well funded development teams. Not content with taking just on just one of them – SAGE has chosen to compete with all four at the same time!

Free maths packages are nothing new of course – there are several good quality, regularly updated open-source packages that one could choose from. For example we have

  • Octave – A numeric-centric application that aims to be source-compatible with the base version of Matlab
  • Maxima – A more symbolic-centric package than Octave that is an open source development of the old commercial Macsyma code.
  • Scilab – Another numeric-centric package that has similar functionality to Matlab but it does not aim to be source compatible in any way.

We also have YACAS, Mathomatic, PARI/GP, GAP, R, Singular and GINAC among others – some of which are very well known in various academic disciplines. So what makes SAGE different?

SAGE is a car

The first major thing I noticed when reading about SAGE is that its developers realised that there is a lot of good code in packages such as Maxima and it would take a long time to develop equivalent levels of functionality from scratch. So, to paraphrase their slogan, rather than re-inventing the wheel they built a car.

In other words they did not try to compete with Maxima by re-implementing its algorithms – they simply included the entire Maxima executable with the base install of SAGE and wrote a SAGE-Maxima interface. So that’s one of the wheels of the car for a start.

For the other wheels they included GAP, PARI and Singular with SAGE so you immediately have access to four different systems from one standard interface – that’s a lot of funtionality. Continuing with the car metaphor I guess we have Python as the engine along with the statistical package, R, as um..the doors? You also have GMP (multi-precision arithmetic), Matplotlib (2d plotting), Tachyon3d (3d plotting) and lots more!

You don’t have to stop with just these included systems if you don’t want to. For example, if you have a copy of Octave on your machine then you can also call that from inside SAGE. Apparently you can even use commercial packages such as Mathematica or Maple although I have yet to try this out myself.

Of course, SAGE is much more than just an interface to existing systems – the developers have also written 250,000 lines of new, SAGE specific code, that adds to this plethora of functionality.

This isn’t just any old car – this is a car with all the optional extras. That gets constantly upgraded. For free!

SAGE uses Python

The next thing about SAGE that stood out for me is the fact that you use the Python scripting language to interact with it. I already know some Python and so, without needing to learn a thing, I already know how to use large parts of SAGE.

SAGE’s use of Python doesn’t just provide a shallower learning curve for Pythonistas, there are a great many other benefits too. In particular, the use of Python gives SAGE access to all of the routines of the extensive numerical library numpy along with the plotting library, matplotlib. These two Python libraries alone provide a reasonable amount of matlab-like functionality before you start considering everything else in the SAGE system.

SAGE has a great user interface

Its been a while since I used any of the other open source maths packages in anger so what I am about to say might be a bit out of date but in general it seems that their user interfaces are a bit, well…primitive. Many of them look just like a terminal prompt with a graphics output window. This is all well and good but when you are used to the pretty, notebook-like interfaces in Mathematica or Maple they all look very last-century.

SAGE uses your web browser as its notebook-like interface and I think it looks great. Here is an example of it in use (shamelessly stolen from here)

Of course you can still use it in good, old fashioned terminal mode if you really want to :)

SAGE has the interact function

SAGE is first and foremost a tool written by researchers for research and so it contains a lot of very advanced mathematics. For example the lead developer, Willian Stein, is very pleased about the fact that SAGE includes code for computing with modular abelian varieties. Now I wouldn’t know what a modular abelian variety was if it hit me over the head (I would welcome an idiot’s guide by anyone willing to write one) but I am sure that this code is very important to those who work with them.

So, bearing in mind that the SAGE developers have worked very hard to include all of this cutting edge functionality, I would like to apologise to them in advance for the fact that the piece of SAGE that really got me interested was the interact command – something that many people may well find frivolous.

In a nutshell interact offers similar functionality to Mathematica’s Manipulate command which I am a HUGE fan of. If you are new here and have no idea why the Manipulate command is so wonderful – check out the Wolfram Demonstrations Project and note that without Manipulate, the project would not exist.

In the second part of this blog post (coming in a few days) I will give you an idea why I think the interact command is so wonderful, what you can do with it and how to use it along with some comparisons with the Manipulate command of SAGE’s competitor, Mathematica. If you can’t wait for me to write the next post and want to see some interact examples right now then check out the interact page on the SAGE wiki.

If you enjoyed this article, feel free to click here to subscribe to my RSS Feed.

TOP