Feeds:
Posts

## Posts Tagged ‘Plot’

Sage beginner’s guide is a book by  Craig Finch, published recently by PACKT publishing.

After spending two weeks looking at different aspects of the book, I can say with property that this is an excellent book, an I’ll recommend it for beginners to medium experienced SAGE users.

Since this is the first book I review, and also the first I own from this publisher, I’d say that its format is quite understandable, and one might learn a lot by following examples… and then, just then, the details are explained. I really love that feature of the writing.

The first chapter, called What can we do with Sage?, shows in about 20 pages some powerful tools available in Sage, from symbolic calculation, linear algebra, ODE’s, to plotting functions in 2D and 3D… even fitting of curves.  I’ll say this is an impressive chapter, and it’s just the start point. Nonetheless, as in any book, one might notice that in some examples the graphics do not correspond to the code, but when you try the code yourself, you get the right ones.

The chapter about Installing Sage, is written in detail, and explain how to install the software in the three major operative systems: Windows, X OS, and Linux. Of course, due to the unstoppable develop of open source software, there’s a delay in the version shown in the book, however, the steps to follow are the same. A nice thing is that it’s explained how to compile the source for multi-core systems.

Getting Started with Sage, shows a huge amount of small tricks, I mean… I’ve been using Sage for about one a half year, and had no idea of plenty of the tricks explained in this chapter. Awesome!!!

All aspects of Sage are exploited, command line, notebook, different cells in the notebook, all the different types of variables available… and their operations. Functions and even a quick introduction to object oriented programming.

Another useful chapter of the book is the one where some differences (and similarities) between Sage and Python are explained. As a example, the use of commands like range, xrange or srange.

Chapters 5 to 8 show with plenty examples and incredible detail uses of Sage in linear algebra, visualization (plotting), symbolic and numerical calculation. Of course, there is no way I can explain how vast the content is, but include:

• Simplifications in symbolic calculation,
• Manipulation and analysis of data,
• Integral transforms,
• Differential equations,
• Series,
• Differential and integral calculus,
• Numerical calculus, et cetera.

Finally, the last two chapters are more a complement for intermediate users, specially with programming knowledge. They cover python programming, say functions, classes and modules, and its uses, and more advanced features of Sage as $\LaTeX$ integration, optimization of numerical calculation (with NumPy and Cython), and an introduction to the interactive mode.

Thus, In a scale from zero to ten I’d give a 9/10 to this book, because managing such a variety of tricks and functions are worth it.

You can check out the book at http://www.packtpub.com/sage-beginners-guide/book

## SAGE tip: Fourier Series Approximation with Interactive mode

After my last post, about Fouries Series, I decided to give a try to the interactive mode of SAGE.

🙂

What did I do?

First I check out the examples worked at the Wiki page. In the section of graphics I got inspired from the post Interactive 2D Plotting by Timothy Clemans and Newton’s Method by William Stein post in the Calculus section. So… there it is!

The code is too long to be posted here… but here it goes anyway

var('x,n,i')

def error_msg(msg): ... print '<p style="font-family: Arial, sans-serif; color: #000;"><span     style="color: red; font-weight: bold;">Error</span>: %s</p>' % msg

...

def a(f, n, init, final): ... x = f.variables()[0] ... L = (final - init)/2 ... coeff = integral(f(x)*cos(n*pi*x/L), (x,init,final))/L ... return coeff

 ... def b(f, n, init, final): ... x = f.variables()[0] ... L = (final - init)/2 ... coeff = integral(f(x)*sin(n*pi*x/L), (x,init,final))/L ... return coeff ... def FS(f, n, init, final): ... x = f.variables()[0] ... L = (final - init)/2 ... return a(f, 0, init, final)/2 + sum(a(f, i, init, final)*cos(i*x*pi/L)+b(f, i, init, final)*sin(i*x*pi/L), i, 1, n) ... 

@interact def interactive_2d_plotter(clr=Color('green'), expression=input_box('x^2', 'Expression', str), x_range=range_slider(-6,6,1,(-4,4), label='X Range'), order=slider([0..100],None,None,3), square=checkbox(True, 'Square'), axes=checkbox(False, 'Show Axes')): ... if expression: ...   try: ...      expression = SR(expression) # turn string into a Sage expression ...   except TypeError: ...      print error_msg('This is not an expression.') ...      return ...   try: ...      xmin, xmax = x_range ...      n = order ...      if square or not axes: ...         print "var('%s')\nplot(%s).show(%s%s%s)" % (expression.variables()[0], repr(expression), 'aspect_ratio=1' if square else '', ', ' if square and not axes else '', 'axes=False' if not axes else '') ...         if square: ...            P = plot(FS(expression, n, xmin, xmax), xmin, xmax, color=clr) + plot(expression, xmin, xmax) ...            P.show(aspect_ratio=1, axes=axes) ...         else: ...            P = plot(FS(expression, n, xmin, xmax), xmin, xmax, color=clr) + plot(expression, xmin, xmax) ...            P.show(axes=axes) ...      else: ...         print "var('%s')\nplot(%s)" % (expression.variables()[0], repr(expression)) ...         P = plot(FS(expression, n, xmin, xmax), xmin, xmax, color=clr) + plot(expression, xmin, xmax) ...         P.show(axes=axes) ...   except ValueError: ...      print error_msg('This expression has more than one variable.') ...      return ...   except TypeError: ...      print error_msg("This expression contains an unknown function.") ...      return

because it’s almost in-understandable 😛

Some pictures!!!

The code is set to give the Fourier approximation of the $f(x)=x^2$ with aspect_ratio = (1,1).

Initial Plot. Approx. of x^2

One can set a non one-to-one aspect_ratio, by un-checking the box,

Initial Plot with-no-square

And we can view the frame as well by checking the other box,

Initial plot no-square and frame

The first box allows us to change the colour, by using a palette,

Initial plot with color-palette

for example, set the colour to red,

Initial plot in red

We can also change the function, to an exponential, $f(x)=e^x$,

Fourier approximation of the exponential

and change the domain of the function,

Changing the interval

or the order of the approximation,

Exponential changing the order of the approximation

I published my sage file on my page (at the end of the page in the attached files)… for the sake of clarity (and completeness).

Enjoy,

Dox

## SAGE tip: Fourier Series Approximation

Inspired by a post in sage-devel (or support) group of SAGE, I came along with this few lines which allows me to plot a Fourier Series Approximation of the line, to a given order,

sage: reset() sage: var('x,i,n') (x,i,n) sage: def b(n): ... return 2.*(-1)^(n+1)/n ... sage: def f(x,n): ... return sum(b(i)*sin(i*x),i,1,n) ... sage: p = Graphics() sage: for n in [1,2,3,4,5,6]: ... p = plot(f(x,n), (x,-pi,pi), color=hue((n+1)/7.0)) + plot(x, -pi, pi, color='black') + text("Fourier Approximation of order %d" %n, (-1,3), fontsize=14, color='blue') ... p ...

and get as result, the series of plots that follows,

1st Fourier Approximation to a Line

2nd Fourier Approximation to a Line

3rd Fourier Approximation to a Line

4th Fourier Approximation to a Line

5th Fourier Approximation to a Line

6th Fourier Approximation to a Line

However, I was not happy ’cause I introduce the Fourier coefficients… So, I did a second try.

sage: reset() sage: var('x,n,i') (x,n,i) sage: f(x) = x^2

 sage: def a(n): ... coeff = integral(f(x)*cos(n*x), (x,-pi,pi))/pi ... return coeff ... sage: def b(n): ... coeff = integral(f(x)*sin(n*x), (x,-pi,pi))/pi ... return coeff ... sage: def FS(n): ... return a(0)/2 + sum(a(i)*cos(i*x)+b(i)*sin(i*x), i, 1, n) ... 

Where I’ve defined the Fourier coefficients and the Fourier Series of a given function $f(x)$, introduced by the user.

With the line

sage: for n in [1,2,3,4,5,6]: ... p = plot(FS(n), (x,-1.1*pi,1.1*pi), color=hue((n+1)/7.0)) + plot(f(x), (x, -1.1*pi, 1.1*pi), color='black') + text("Fourier Approximation of order %d" %n, (0,-2), fontsize=14, color='blue') ... p ...

One get the Fourier Series Approximation for $f(x)=x^2$,

1st Approximation for the parabola

2nd Approximation for the parabola

3rd Approximation for the parabola

4th Approximation for the parabola

5th Approximation for the parabola

6th Approximation for the parabola

#### NOTE…

• The use of the last program is restricted to the interval $[-\pi,\pi]$.
• In order to find the Fourier coefficients the integrals might be doable… so no every function $f(x)$ can be shown as a Fourier series approximation.
• I tried to define the above using numerical_integrategral command, but didn’t work. Does anyone knows why?
• I also tried to use range command instead of a list for the loop… Didn’t work!!! Any clues?
• Ok, that was it. Enjoy!!!

DOX.

## SAGE tip: Graphs of Elementary Numerical Integrals

Looking on the notebook worksheets publish on sagenb I found a very interesting application of the interactive mode, Interactive.

Since one can not look the result of the published notebooks, I use its code to playing around a little bit, so here are the plots.

The default function to be integrated is $\sin(x^2)+2$, the interval of integration is set $[-1,3]$, the number of partitions of the interval is 4, and the method is the mid-point,

Integration by mid-point method. Partition = 4

We can see the visual integration, the analitic result, the numerical one, and the error. 🙂 Nice, Isn’t it?

Let’s change the number of partitions, say to 10,

Integration by mid-point method. Partition = 10

Much better! But now, let’s try the other methods… left-point,

Integration by left-point method. Partition = 10

The right-point,

Integration by right-point method. Partition = 10

The upper-point,

Integration by upper-point method. Partition = 10

The lower-point,

Integration by lower-point method. Partition = 10

The trapezoid method,

Integration by Trapezoid method. Partition = 10

which is one of the best.

But finally the Simpson method,

Integration by Simpson method. Partition = 10

Impressive!!!

So, I think it’s a good idea to give a try to the interactive mode in SAGE, and if you go thru the code you’ll find out it’s not as difficult as it seems.

Enjoy!

Dox

## SAGE tip: Changing the ticks of a plot

This trick can be found at the plot function documentation, and it was a new command from SAGE(math) v.4.5 or v.4.6.

Say we want to plot the sine function,

plot(sin, -7, 7, axes_labels=['$x$','$\\sin(x)$'], fontsize=14, color='red')

we’ll get

Original sine ticks

Now, let’s change the ticks,

plot(sin(x), (x, -7, 7), ticks=pi/2, tick_formatter=pi, axes_labels=['$x$','$\\sin(x)$'], fontsize=14, color='red')

We’ll get,

Ticks every half pi.

One can also insert ticks at will!!!

plot(2*x+1,(x,0,5),ticks=[[0,1,e,pi,sqrt(20)],2],tick_formatter="latex")

yields,

Ticks at will

Enjoy!

DOX

## Graphics Array in Sage(math)

For a publication I was working on, I plotted functions in  PDF format. However, the journal ask me to handle them in EPS format.

“What’s the point?” you might ask. Well, since I installed Lucid Lynx (a clean installation), the files of those graphic were gone… Fool of me, you will say, but really, I never thought that this days journals DO NOT accept PDF files!!!!

Who cares! to the point.

First I tried with the convert command

for i in *.pdf; do convert $i$(echo $i| sed -e s/pdf/eps/g); done It did the job, but the quality of the plots was compromised. Then, I move to Sage(math), and re-discover the function ‘graphics_array’, and try this, p1 = plot(Vn(x, 1, 3), (x,-5,5), color='black', thickness=2) p1 += plot(Vp(x, 1, 3), (x,-5,5), color='black', thickness=2, linestyle='-.', \ axes_labels=[r'$\xi^\prime', r'$V_{qm}(\xi^\prime)$'], fontsize=17)
p2 = plot(Vn(x, 3, 3), (x,-5,5), color='black', thickness=2)
p2 += plot(Vp(x, 3, 3), (x,-5,5), color='black', thickness=2, linestyle='-.', \
axes_labels=[r'$\xi^\prime$',r''], fontsize=17)
p3 = plot(Vn(x, 5, 3), (x,-5,5), color='black', thickness=2)
p3 += plot(Vp(x, 5, 3), (x,-5,5), color='black', thickness=2, linestyle='-.', \
axes_labels=[r'$\xi^\prime$',r''], fontsize=17)

… a little explanation?! p1, p2 and p3 are the graphics I’d like put into an array, each of them contain 2 plots (both black because otherwise they’ll make me pay an incredible amount of money… crazy people!), and them try the graphics_array,

ga = graphics_array([p1, p2, p3])
ga.show(frame=True, axes=False, figsize=[12,8])

and obtain something like this,

First try with graphics_array

Yeah babe!!!… What???!!! It’s not all right! What happened with the axis labels, the font size, and so on?

Second try: let’s see if the plots are working one by one

p1

This is the right p1

p2

The right p2

p3

The right p3

The are alright! So, What happened? Let me run again the graphics_array commands

ga = graphics_array([p1, p2, p3])
ga.show(frame=True, axes=False, figsize=[12,8])

What did I get?…

The final result was as I wanted to be! 🙂

MORAL: Make Sage(math) show you the plot, one by one, before make them into an array!

Yeah… I almost forgot it!

My goal was to save it as an EPS file, so after getting the looked graph, the command is

ga.save(frame=True, axes=False, figsize=[12,8], \
filename='/path/to/directory/name-of-plot.eps')

Cya all!

## 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)
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$.