Feeds:
Posts

## Contour Plot in Sage and Matplotlib

Today I was playing around with Matplotlib and Sage(math) for plotting the relativistic addition of velocities.

First I tried the classic 3-dimensional plot in Sage,

var(‘x,y’)
p = plot3d((x+y)/(1+x*y), (x,0,.99), (y,0,.99), color=hue(0.8))
p.save(‘Vel-3d.png’)

Plot in 3D of velocities addition

However the plot was not so enlighten. So I tried a contour plot,

var(‘x’)
p = contour_plot((x+y)/(1+x*y), (x,0,.99), (y,0,.99), contours=[0.3,0.2,.5,.7,.9,.99], cmap=’hsv’, labels=True, fill=False,  fontsize=14)
fig = p.matplotlib(axes_labels=[‘$V/c$’,’$v/c$’])
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig.set_canvas(FigureCanvasAgg(fig))
axes = fig.get_axes()[0]
axes.minorticks_off()
axes.set_xticks([float(j/10) for j in range(0,11)])
axes.set_yticks([float(j/10) for j in range(0,11)])

Addition of velocities contour plot in Sage(math)

Finally, I plot it in Matplotlib

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0., 0.99, 0.01)
y = np.arange(0., 0.99, 0.01)
X, Y = np.meshgrid(x, y)
curve = (X+Y)/(1 + X*Y)
cs = plt.contour(curve, [.2,.3,.5,.7,.9,.99])
plt.clabel(cs);
plt.xlabel(r’$\frac{V}{c}\times 100$’, fontsize = 15)
plt.ylabel(r’$\frac{v}{c}\times 100$’, fontsize = 15)
plt.show()

Undoubtly, the control of the plot using Matplotlib is impressive, but somehow I do not get what the mesh does that it changes the scale of the axes $x$ and $y$.

Enjoy!

## Pre-requisites.

I don’t know how much of it its really needed, but I install the whole Sun’s Java 6 packages,

$sudo apt-get install sun-java6-jdk sun-java-6-jre sun-java6-pluging sun-java6-source sun-java6-bin  For sure you’ll need the jdk and plugin one… If your internet connection is slow you might try installing these two first and try the above command. ## Configuration of Java for Mozilla. For enable Java plugin on Firefox 3.6, $ sudo update-alternatives --install /usr/lib/mozilla/plugins/libjavaplugin.so \
mozilla-javaplugin.so /usr/lib/jvm/java-6-sun/jre/lib/i386/libnpjp2.so 50


Now it’s time to restart your browser.

For checking that the plugin is enabled, open your Firefox browser and type

about:plugins


in the address line, there must be the Java application enabled.

## Bonus Track.

After doing the above steps, I realize that got a bonus…

• The Java Plugin was enabled also for conkeror browser.
• Since I use Firefox as the browser for Sage(math), the 3D plots are visible now.

I was playing with Sage(math) because I wanted to manage (a bit) the presentation of the plots. Here is what I found out! (most of it is in Sage help)

## Color of Plots.

For changing the color of the plot, use the option color,

sage: plot(sin, -3, 3, color='red')

and you’ll get

Red Sine Function

Nice! but not enough.

One can draw recurrent plots by using a for command,

sage: for n in range(1,6):
... plot(sin(n*x), (x, -3, 3), color=hue(n/5.0))

but this code gives 5 different plots, if you want only one try this

sage: p = plot( sin, -3, 3, color=hue(1/5.0))
sage: for n in range(2,6):
... p += plot(sin(n*x), (x, -3, 3), color=hue(n/5.0))
...
sage: p


and the result is

Plot of multiple sine functions in colors

The command for adding text to plots is text (very intuitive, Isn’t it?), and the parameters are, the actual text you’d like to insert between single quote marks, the coordinates, and any other characteristic… as color.

Additionally, the text environment accepts mathematical LaTeX inputs by using the dollar signs.

sage: p = plot(sin(x/10.0), -10, 10, color=hue(1/6.0))
+ text('$n$=1', (12,1), color=hue(1/6.0))
sage: for n in range(2,6):
... p += plot(sin(n*x/10.0), -10, 10, color=hue(n/6.0))
+ text('$n$=%s'%n, (12,1/n), color=hue(n/6.0))
sage: p

and get,

Note that the text may include running parameters, in the above example the running parameter is $n$, and is called in the text environment as %s and later one explain that the value to insert is $n$ via %n.

NOTE 2: The coordinates of the text might be also changing values.

NOTE 3: The fontsize and horizontal_alignment options are available, for example

sage: text('$E$=%s'%Energy, (5.2, 1.2),
horizontal_alignment='right', fontsize=15, color='black')

## Nice Example.

Try this!

reset()
def Harm_Osc(n, x):
return sqrt(1/(2^n*factorial(n)))/(pi)^(0.25)*e^(-x^2/2)*hermite(n,x)
p = plot(x^2/2, (x, -3.2, 3.2), color='black')
+ text('$x^2/2$', (3.9, 5), color='black', fontsize=13)
for n in range(5):
p += plot(Harm_Osc(n, x)/2 + n + 0.5, (x, -5, 5), color=hue(n/5.0), fill=n + 0.5)
+ text('$\Psi_%s$' %n, (5.2, n+0.5), color=hue(n/5.0), fontsize=13)
show(p, axes_labels=['$x$','$E$'])

😉

You’ll get this,

Wave functions for the quantum harmonic oscillator

This example got colors, text, running text, running color, axes labeling, LaTeX text, fill plot… very complete!

Last week I was trying to integrate a power of the Hyperbolic Tangent  (tanh) in sage, so I first try,

sage: n,x = var('n,x')
sage: integrate(tanh(x)^n, x)


but Sage didn’t integrate it. So I impose $n$ to be an integer,


sage: n,x = var('n,x')
sage: assume(n, 'integer')
sage: integrate(tanh(x)^n, x)

and still nothing. However, for specific values of $n$ it worked,

sage: for n in range(1,6):
...  integrate(tanh(x)^n, x)
...

the results were shown.
In the other hand, Mathematica could solve the integration in general,

Integrate[Tanh[x]^n, x]

in terms of Hyperbolic Functions (which Maxima does not manages). Even in the case of specific values of $n$, the given results were much nicer because the answer were given in term of hyperbolic functions instead of exponential.
Then, I decide to try the Sage-Mathematica synapses.
What do we need?

Mathematica installed in the computer.
The License information of Mathematica (even if you have already registered it)
A working Sage installation.

Proceed…
Open a terminal and call a sage subshell,

$sage -sh and call the mathematica kernel,$ math

Here you will be asked to provide the license information. NOTE: It is possible that if runs without the information of the license, in that case you are ready to use Mathematica within Sage.
After provide the information you are ready.
Using it!
The way of using is a bit weird, at the beginning,  for integrate the sine function, use this,

sage: mathematica.Integrate(sin(x), x)

Explaination:
Since we are welling to use Mathematica kernel, the first word would be mathematica, followed by a Mathematica command separated by a point. Then, using Sage notation the argument.
This would work! However, the answer is presented in Mathematica notation. If you’d like to have the answer in Sage notation, use something like

sage: eq = mathematica.Integrate(sin(x), x); eq._sage_()

That’s it.
I’d like to thank to schilly for his help.


I’ve been trying Sage(math) for the last three weeks, and I can say it’s a charming piece of software. Works very well, the IRC channel is really, really helpful, the interface is simple, the Python platform is rather natural to manage, evolves quickly… and so on.

However, there are some weak points I’d like to comment…

• Documentation: Since Sage(math) use about 70 different applications, the documentation is FAR of being complete. It would be useful if the documentation is improved, at least if it refers to, say, Maxima documentation… or Numpy… etc.
• Hypergeometric Functions: Besides the confluent one, the hypergeometric functions are left behind. I guess the problem is the maxima support of Special Functions.
• Browser Integration: There are still some weak points in browsers other than firefox… like Chromium-browser. A.f.a. I know, Chromium has problems opening new worksheets, and with some permissions settings.

So, I recomend using firefox as the main browser for Sage(math) and if possible integrate it with other calculation programs like Maple or Mathematica. And finally look up further into Maxima, and other pieces of Sage documentation, as well as using the IRC channel (#sage-devel) an google groups for asking questions.

## Installing and Using SageTeX.

A few minuted ago I could install and use the sagetex package for Sage(math). I’d like to thank ElMonkey for helping me via the IRC channel #sage-devel.

## Pre-requisites.

It is assumed that you have installed

• A LaTeX compiler,
• A LaTeX editor,
• and Sage(math)

all of them configured and working properly.

Get the last version of the package in http://www.sagemath.org/packages/optional/.

## Installing the Package.

My Sage script is located in a sub/sub/sub/subfolder/Sage-4.3.1 (from my HOME folder), so when I want to running it, I should type

$sub/sub/sub/subfolder/Sage-4.3.1/./sage It isn’t nice to repeat this one and again, every day. Thus, I created an alias. Open the .bashrc file in your editor (gedit for example) $ gedit .bashrc


add (at the end of the file) the line

alias sage='/path/to/your/sage/folder/./sage'


which in my example would be,

alias sage='/home/doxdrum/sub/sub/sub/subfolder/Sage-4.3.1/./sage'


Save and close the editor. Now in the terminal,

$source .bashrc  and from now on I just type $ sage

for running the program.

### The real installation.

Now, type in the terminal

$sage -i sagetex-2.2.1.spkg and that’s it. ## Configuration. After the installation, a new folder is placed into the Sage folder. Look into local/share/texmf. All files (and folders) inside it must be copied to the LaTeX tree. In a Linux distribution the LaTeX tree should be placed in /usr/share/texmf/tex/latex $ sudo cp -r /path/to/Sage-4.3.1/local/share/texmf \
/usr/share/texmf/tex/latex
$sudo mktexlsr /usr/share/texmf/tex/latex This should work. However, if it doesn’t… the desperate method is to copy the sagetex.sty from /path/to/Sage-4.3.1/local/share/texmf to the folder of the TEX file. ## The TeX File. It is time to create a file.tex, just as any other TEX file. Add the line \usepackage{sagetex} to the preable. ### Compiling the TeX file. When you run $ pdflatex file.tex

the compilator exits with errors… but you get a file.sage, sage-compile it and run pdflatex again,

$sage file.sage$ pdflatex file.tex


There it is!!!

A resume compilation line could be

\$ pdflatex file.tex && sage file.sage && pdflatex file.tex

Enjoy it!