Feeds:
Posts
Comments

Posts Tagged ‘Matlab’


Last weekend, I wrote a program in SAGE that list all possible irreps of a Lie group, one specified the group (in Cartan’s classification) and the maximum sum of the Dynkin labels.

Check the notebook in here.

Since I’m not a programmer, please feel free to leave comments, specially if you find ways to optimize the program

Cheers,

DOX

Read Full Post »


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

Read Full Post »


In a previous post we discuss the definition of the coordinated patch on a manifold, how to define differential forms, wedge them or calculate their exterior derivative… even simplify’em.

This time a zero form will be defined and a list of forms will be created… So, let’s begin!

Define a 0-form

Once created the coordinated patch and the differential forms algebra

sage: reset()
sage: var('t,x,y,z')
sage: U = CoordinatePatch((t,x,y,z))
sage: Omega = DifferentialForms(U)

A 0-form is defined as an element of \Omega^0(U), but the value of the 0-form is given inside the declaration command,

sage: A = DifferentialForm(Omega, 0, exp(x*y))

I tried addition, multiplication, wedge product and exterior differentiation on 0-forms and they worked!

Of course you can combine them with forms of different degrees.

New method of defining a form

I wrote to Joris this morning… but before he was able to answer, from the documentation of the differential form package.

When one calls the generators of the differential form,

sage: Omega.gen(1)
dx

and the result is a differential form… Thus, one can assign a form as follow,

sage: A = sin(x)* Omega.gen(2)
sage: B = cos(y) * Omega.gen(0)
sage: C = sin(z) *Omega.gen(1)
sage: D = cos(y) * Omega.gen(2)

And this forms can be wedged, differentiated, et cetera. 🙂

List of forms

Finally, after discovering the above behavior I tried the following, a list of differential forms ;-), for example,

sage: pro = matrix([[A, B], [C, D]])
sage: for i in range(2):
...       for j in range(2):
...           show(pro[i,j].diff())

returns
cos(x)dx\wedge dz
sin(y)dx\wedge dy
-cos(z)dy\wedge dz
-sin(y)dy\wedge dz

This implies that somehow one can manage a series of forms by using list properties… I expect to go deeper on this subject in the future! 😀

Enjoy people!!!

Dox

Read Full Post »


This code is supposed to be (if some one does the work in the future) located in sage.tensor.differential_form_element.

The code presented below is a slight modification of Joris code for differential forms manipulation on SAGE.

Needed modules

from sage.symbolic.ring import SymbolicRing, SR
from sage.rings.ring_element import RingElement
from sage.algebras.algebra_element import AlgebraElement
from sage.rings.integer import Integer
from sage.combinat.permutation import Permutation

The advantage of using this is that, tensors defined here are an Algebra element, not just a python object as in the previous code.

The sage.combinat.permutation won’t be used (yet), but could be useful if tensor symmetries are defined.

TensorFormatter

class TensorFormatter:
    r"""
    This class contains all the functionality to print a tensor in a
    graphically pleasing way.  This class is called by the ``_latex_`` and
    ``_repr_`` methods of the Tensor class.
    """
    def __init__(self, space):
        r"""
        Construct a tensor formatter.  See
        ``TensorFormatter`` for more information.
        """
        self._space = space

    def repr(self, comp, fun):
        r"""
        String representation of a primitive tensor, i.e. a function
        times a tensor product of d's of the coordinate functions.

        INPUT:

        - ``comp`` -- a subscript of a differential form.

        - ``fun`` -- the component function of this form.

        EXAMPLES::

            sage: from sage.tensor.tensor_element import TensorFormatter
            sage: x, y, z = var('x, y, z')
            sage: U = CoordinatePatch((x, y, z))
            sage: D = TensorFormatter(U)
            sage: D.repr((0, 1), z^3)
            'z^3*dx@dy'

        """

        str = "@".join( \
            [('d%s' % self._space.coordinate(c).__repr__()) for c in comp])

        if fun == 1 and len(comp) > 0:
            # We have a non-trivial form whose component function is 1,
            # so we just return the formatted form part and ignore the 1.
            return str
        else:
            funstr = fun._repr_()

            if not self._is_atomic(funstr):
                funstr = '(' + funstr + ')'

            if len(str) > 0:
                return funstr + "*" + str
            else:
                return funstr

    def latex(self, comp, fun):
        r"""
        Latex representation of a primitive differential form, i.e. a function
        times a tensor product of d's of the coordinate functions.

        INPUT:

        - ``comp`` -- a subscript of a differential form.

        - ``fun`` -- the component function of this form.

        EXAMPLES::

            sage: from sage.tensor.tensor_element import TensorFormatter
            sage: x, y, z = var('x, y, z')
            sage: U = CoordinatePatch((x, y, z))
            sage: D = TensorFormatter(U)
            sage: D.latex((0, 1), z^3)
            'z^{3} d x \otimes d y'

        """

        from sage.misc.latex import latex

        str = " \otimes ".join( \
            [('d %s' % latex(self._space.coordinate(c))) for c in comp])

        if fun == 1 and len(comp) > 0:
            return str
        else:
            funstr = latex(fun)

            if not self._is_atomic(funstr):
                funstr = '(' + funstr + ')'

            return funstr + " " + str

    def _is_atomic(self, str):
        r"""
        Helper function to check whether a given string expression
        is atomic.

        EXAMPLES::

            sage: x, y, z = var('x, y, z')
            sage: U = CoordinatePatch((x, y, z))
            sage: from sage.tensor.tensor_element import TensorFormatter
            sage: D = TensorFormatter(U)
            sage: D._is_atomic('a + b')
            False
            sage: D._is_atomic('(a + b)')
            True
        """
        level = 0
        for n, c in enumerate(str):
            if c == '(':
                level += 1
            elif c == ')':
                level -= 1

            if c == '+' or c == '-':
                if level == 0 and n > 0:
                    return False
        return True

The only I’ve changed here is “DifferentialForm” by “Tensor” and “\wedge” by “\otimes”

The above code allows to write the tensor product in a basis, dx^1\otimes\cdots\otimes dx^n. The chosen symbol for denoting the tensor product was @.

Tensor Class

This code is incomplete due to:

  • I’ve not defined the TensorsAlgebra, which should be done in parallel.
  • There are a lot of attributes not presented in this class.
  • class Tensor(AlgebraElement):
        r"""
        Tensor class.
        """
    
        def __init__(self, parent, degree, fun = None):
            r"""
            Construct a tensor.
    
            INPUT:
    
            - ``parent`` -- Parent algebra of tensors.
    
            - ``degree`` -- Degree of the tensor.
    
            - ``fun`` (default: None) -- Initialize this differential form with the given function.  If the degree is not zero, this argument is silently ignored.
    
            EXAMPLES::
    
                sage: x, y, z = var('x, y, z')
                sage: F = Tensors(); F
                Algebra of tensors in the variables x, y, z
                sage: f = Tensor(F, 0, sin(z)); f
                sin(z)
    
            """
    
            from sage.tensor.tensorss import Tensors
            if not isinstance(parent, Tensors):
                raise TypeError, "Parent not an algebra of tensors."
    
            RingElement.__init__(self, parent)
    
            self._degree = degree
            self._components = {}
    
            if degree == 0 and fun is not None:
                self.__setitem__([], fun)
    
        def __getitem__(self, subscript):
            r"""
            Return a given component of the tensor.
    
            INPUT:
    
            - ``subscript``: subscript of the component.  Must be an integer
            or a list of integers.
    
            EXAMPLES::
    
                sage: x, y, z = var('x, y, z')
                sage: F = Tensors(); F
                Algebra of tensors in the variables x, y, z
                sage: f = Tensor(F, 0, sin(x*y)); f
                sin(x*y)
                sage: f[()]
                sin(x*y)
            """
    
            if isinstance(subscript, (Integer, int)):
                subscript = (subscript, )
            else:
                subscript = tuple(subscript)
    
            dim = self.parent().base_space().dim()
            if any([s >= dim for s in subscript]):
                raise ValueError, "Index out of bounds."
    
            if len(subscript) != self._degree:
                raise TypeError, "%s is not a subscript of degree %s" %\
                    (subscript, self._degree)
    
            """sign, subscript = sort_subscript(subscript)"""
    
            if subscript in self._components:
                return sign*self._components[subscript]
            else:
                return 0
    
        def __setitem__(self, subscript, fun):
            r"""
            Modify a given component of the tensor.
    
            INPUT:
    
            - ``subscript``: subscript of the component.  Must be an integer or a list of integers.
    
            EXAMPLES::
    
                sage: F = Tensors(); F
                Algebra of tensors in the variables x, y, z
                sage: f = Tensor(F, 2)
                sage: f[1, 2] = x; f
                x*dy@dz
            """
    
            if isinstance(subscript, (Integer, int)):
                subscript = (subscript, )
            else:
                subscript = tuple(subscript)
    
            dim = self.parent().base_space().dim()
            if any([s >= dim for s in subscript]):
                raise ValueError, "Index out of bounds."
    
            if len(subscript) != self._degree:
                raise TypeError, "%s is not a subscript of degree %s" %\
                    (subscript, self._degree)
    
            """sign, subscript = sort_subscript(subscript)"""
            self._components[subscript] = SR(fun)

    Ok, so again I’ve changed “DifferentialForm(s)” by “Tensor(s)”, drop the permutation of indices (’cause tensors do not need to be neither symmetric nor anti-symmetric.

    I’ll keep working with this code… It’s all by now. Oh! I’ll post next week the rest of the code based in Sergey’s GRPy.

    Enjoy.

    Dox

    Read Full Post »


    From time to time when one works with operators, such as in Quantum mechanics, something like an exponential of the operator appears (this is also the case in many areas of Mathematics like group theory of differential geometry). This exponentiation of a matrix should be understood as the series expansion of the exponential.

    SAGE knows how to do this exponentiation,

    sage: reset()
    sage: var('a,b,c', domain=RR)
    sage: A = a*I*matrix([[0,1],[1,0]])
    sage: B = b*I*matrix([[0,-I],[I,0]])
    sage: C = c*I*matrix([[1,0],[0,-1]])
    sage: A.exp()
    [1/2*(e^(2*I*a) + 1)*e^(-I*a) 1/2*(e^(2*I*a) - 1)*e^(-I*a)]
    [1/2*(e^(2*I*a) - 1)*e^(-I*a) 1/2*(e^(2*I*a) + 1)*e^(-I*a)]
    sage: B.exp()
    [   1/2*(e^(2*I*b) + 1)*e^(-I*b) -1/2*(I*e^(2*I*b) - I)*e^(-I*b)]
    [ 1/2*(I*e^(2*I*b) - I)*e^(-I*b)    1/2*(e^(2*I*b) + 1)*e^(-I*b)]
    sage: C.exp()
    [ e^(I*c)        0]
    [       0 e^(-I*c)] 

    The only problem here is that, even when the relations are simple in this example, I’ve not found a `trivial’ way of simplifying the matrix elements of the exponentiation, not even with the procedure post in here. I didn’t try with the rewrite package

    Comments are welcome!

    Enjoy.

    Dox

    Read Full Post »

    Older Posts »