Feeds:
Posts

## Posts Tagged ‘Tensors’

On a previous post I described how to change the LaTeX options of the Cadabra notebook.

I collaborate with a colleague, who uses the standard cadabra installation. Therefore, If I write a Cadabra notebook, he needs to pullback the personalised notebook to the standard one. The pullback script can be downloaded here!!!

Created: 2014-02-18 Tue 20:20

Emacs 24.3.1 (Org mode 8.2.5h)

Validate

Read Full Post »

Just by playing around with CADABRA, I found out the existence of a super-useful LaTeX package, called breqn, which allows to break long equations at the edge of the page… like the wraping feature of most text editors.

However, when one manipulates really long expressions, I’d like to break these long equations through the page. I’m still looking for this feature… in that case I can improve even more the behaviour of cadabra‘s notebook, when compiling it to LaTeX.

Any suggestions???

Cheers!

Read Full Post »

Goal: a cadabra notebook more LaTeX friendly.

1. I run a Debian system. Don’t know why, but the original source code in the git repo didn’t work!!!What did I do? I downloaded the code from the Debian repository.
$sudo apt-get build-dep cadabra # Install all dependences$ mkdir -p ~/Software # Create a folder to download the source
$cd ~/Software # Move to the folder$ apt-get source cadabra # Download the source code (from Debian)
2. On the cadabra folder created through the last command line, I looked for the window.cc file and open it
$emacs cadabra-1.29/gui/window.cc & 3. On the window.cc file I changed: • The LaTeX package color by the improved xcolor, by changing the string << "\\usepackage[usenames]{color}\n" by << "\\usepackage{xcolor}\n" • I added the LaTeX package listings, which improves the verbatim properties (among other things). Right after the mentioned xcolor line, I added the following << "\\usepackage{listings}\n" << "\\lstset{\n" << " basicstyle=\\small\\color{blue}\\ttfamily,\n" << " breaklines=true,\n" << " columns=fullflexible,\n" << " commentstyle=\\color{gray!60},\n" << " morecomment=[l]{\\%\\%},\n}" This allows the Cadabra code to break at the end of the line instead of going out of the page, when compiled to LaTeX (similar to what breqn does on equations). • Now, I changed on the DataCell::c_input: case,1 the strings {\\color[named]{Blue}\\begin{verbatim}\n by \\begin{lstlisting}\n, and \n\\end{verbatim}}\n by \n\\end{lstlisting}\n.Far below, the lines with the code if(ln=="{\\color[named]{Blue}\\begin{verbatim}") { should be changed to if(ln=="\\begin{lstlisting}") {, as well as else if(ln=="\\end{verbatim}}") { should be changed to else if(ln=="\\end{lstlisting}") {. • Save all the changes 4. Finally, time to compile $ ./configure
$make$ sudo make install
5. If your compilation/installation went through, and you try to open an old cadabra notebook (a notebook created with the original cadabra code), the program will complain that the file is not compatible… but I created a small script to transform the old files into new files! Download it here!!USAGE:
\$ ./transf_cadabra oldfile.cnb newfile.cnb

## Footnotes:

1This is located a few lines below the lines where the LaTeX preamble is defined

Created: 2014-02-18 Tue 10:09

Emacs 24.3.1 (Org mode 8.2.5h)

Validate

Read Full Post »

## SAGE tip: More about Differential Forms

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 »

## Mathematics, Mathematica and other softwares

This post is more about a personal opinion.

Most of the followers of my blog know that I’m a devote Linux user, and that I prefer Open Source than any other software.

It is clear than most business people prefer to spend money for a piece of software which get the job done. And additionally, developers will align with the mainstream vendor… or in some cases, money convince them.

The last to months I’ve been working in some supergravity theory, and you might imagine that even a easy calculation is messy… at least, and will take a huge amount of time to complete.

On the other hand Mathematica offers a huge (really huge) toolkit for mathematicians, physicists, economists, and so on. I admit it… I sort of hate to use Mathematica, really do!, but although we all know is amazing as a toolkit.

Nonetheless, most scientist (specially those who grow up using this kind of software), trust the results as if it was not possible to be wrong!!! But if you look further…. there is a book, as enormous as Mathematica user’s guide, of bugs :-S

A year ago one of my office mate found two bugs: one in an integration routine, and another in a loop routine!!!! A LOOP ROUTINE… Do you know someone who has never used a loop routine? How many possible errors have been publish and propagated?! Moreover, I found a bug myself… in the plot function 😐

Since then I use SAGE… or Python, so I’ve spent a lot of time learning, developing and proving routines, asking in the help channels and so on!

I know that this alternatives are far away from Mathematica or Maple or whatever your favourite calculation software is… but imagine!

Today I found a Mathematica package for computing GR tensors, you can use differential forms, first order formalism, redefine quantities in term of vielbeins, write equations using differential forms (with Hodge star and so on)… Incredible! Isn’t it?

Who develop this package? It was not Wolfram!!!! If I were the developer of this marvelous package, I’d prefer to kill myself before writing such a thing for a product which is not available for everyone. Exaggeration?! yes, may be… but I’m citizen of a wealth country, full of poor people. Yes, I also know that any pirate page has a cracked copy of Mathematica… but why should I crack a program?

I don’t want to crack Mathematica… I want an open source software which do as Mathematica. Sorry, I correct: I want an open source software which do BETTER than Mathematica.

My bet is on SAGE, and that’s why I’m willing to contribute with this project.

Live wide and prosper! Enjoy!

Dox

Read Full Post »

## SAGE tip: GRmodule. Day 07.

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 »

## SAGE tip: GRmodule. Day 06.

I’ve just updated the SAGE worksheet which uses the definitions described in the previous posts.

• There are some explanations in text format
• The code has been hidden… because is long.
• Moreover… I’ve discover something really amazing! Joris Vankerschaver‘s code of the differential form package in SAGE. Thus, I could use some ideas from Joris’ code to improve GRmodule. Nice, Isn’t it?

Let’s hope I could so something nice this weekend!

Don’t forget check the worksheet, and post some comment for feedback! 😉

Enjoy!

Dox

Read Full Post »

Older Posts »