Feeds:
Posts

Posts Tagged ‘Online’

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

Two days ago I was trying to expand in series a lot of functions… so I ask myself, Could it be done in SAGE? It should be possible… but, How? 😛

Solution by Andrzej Chrzeszczyk

sage: var('r');
sage: f=2*r/sinh(2*r)
sage: f.taylor(r,0,5)
14/45*r^4 - 2/3*r^2 + 1
sage: maxima(f).powerseries('r',0)
-4*r*'sum((2^(2*i2-1)-1)*2^(2*i2-1)*bern(2*i2)*r^(2*i2-1)/
(2*i2)!,i2,0,inf)

This solution uses a power series expansion from maxima… really nice feature! Isn’t it?
Ah… and this expansion is around $r=0$.

If one would like the asymptotic expansion $r\to\infty$,

sage: maxima(f).powerseries('r',infinity)
-4*r*'sum((2^(2*i3-1)-1)*2^(2*i3-1)*bern(2*i3)*r^(2*i3-1)/
(2*i3)!,i3,0,inf)

However, note that this expansion coincides with the previous one, i.e., it’s the function itself. It couldn’t be that perfect. 😉

Solution by Francois Maltey

Use the Taylor command of SAGE,

• Around zero
sage: taylor (2*x/sinh(2*x), x, 0, 10)
-292/13365*x^10 + 254/4725*x^8 - 124/945*x^6 + 14/45*x^4 - 2/3*x^2 + 1
• Around infinity… a trick! change $x\mapsto 1/x$ and expand around zero 🙂
sage: taylor (2*1/x/((exp(2/x)-exp(-2/x))/2), x, 0, 12)
4*e^(-10/x)/x + 4*e^(-6/x)/x + 4*e^(-2/x)/x
• Thank you guys!

Enjoy!

Dox

A quick tip today, thanks to Jason from the google group for the tip. 🙂

I must admit to be a LaTeX addict, I’ve never used a wysiwyg editor… I do everything in LaTeX code,

• Reports,
• Magazine articles,
• Letters,
• Scientific articles,
• Tried once to do a music sheet,
• Posters,
• I tried sagetex,
• and plenty more!…
• When I discover that SAGE notebook accepted LaTeX code, that help convince me to use it!!!

Example:

%latex
$\vec{F} = m\vec{a}$

generates

$\vec{F} = m\vec{a}$

I use this method to explain in the calculation worksheet what I’m doing. However, when trying to print the sheet the LaTeX code was around and the file was messy’.

If you use either %hide or %hideall character, the LaTeX output is hidden (at least when you want to print). Sometimes I get the cose hidden as well in the notebook, but thats not that important as hiding it when printing 🙂

Thank you again Jason.

Cheers!!

Dox

As I’ve mention before, actually I’m dealing with some messy supergravity calculations. 😛 Unlike most of my colleges, I don’t use Mathematica but their open source SAGE (applauses).

Declaring (weird) Variables

Through the calculations I should care about 10 dimensions, with a 5 dimensional restriction parametrized by  five different angles, which I call $(\theta,\phi,\bar{\psi},\bar{\theta},\bar{\phi})$… thus, naturally the question of whether a variable can be declared in a way s.t., when using the function show for printing the results, the latex equivalent to my expression is shown, appears!

The answer came a few minutes ago! Thanks to Niels Bruin via sage-devel google group. 😉

sage: var("bps", latex_name=r"\hat{\psi}") bps sage: expr = sin(bps) sage: show(expr)

returns $\sin(\hat{\psi})$. 😀

Really neat!!!

Recently I re-discover the “office”-like functionality of sage notebook. Have you notice the thin blue line that appears when the cursor is about to reach the calculation window by above?

If you click on the blue line, an intermediate calculation line will appear. Whilst, if you click on the line while holding the Shift key, a sort of office suite environment is opened!!!

There you can write in a LibreOffice style!!!

That’s not all. Jason Grout has pointed out to me that one can insert LaTeX equations in this environment just by using the dollar-dollar ($<your code>$) for inline equations, or doubledollar-doubledollar ($$<your code>$$) for centered-nonumbered equations.

Fabulous, Isn’t it?!

That’s all for now! 😉

Enjoy.

DOX

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.

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