How to install SAGE in OpenSUSE

Python

After almost five years using gentoo I decided, about one year ago, to switch to OpenSUSE. I am a KDE user and I don't have enough time to take care of my computer as it was a pet (this was the feeling I had dealing with gentoo).

One of the lessons learned with gentoo was that, most of times, fixing build scripts is not that difficult. It takes some time and research, but configuration scripts are just scripts at the end.

If you try to compile SAGE in either OpenSUSE 11.2 or 11.3 you will get a weird bash error. This is due to the fact that bash is dynamically linked with libreadline in some modern distributions (Arch linux has this issue too). The readline configuration script for the SAGE's local readline version has an exception for OpenSUSE 11.1, and only 11.1.

You only have to go to the spkg folder where the readline spkg is. In SAGE, a spkg is only a tarball of the source directory. Untar the spkg and change the following block in the build and install script (spkg-install)

if [ -f /etc/SuSE-release ]; then
    if [ `grep 11.3 /etc/SuSE-release > /dev/null; echo $?` -eq 0 ]; then
        echo "OpenSUSE 11.3 detected"
        if [ -d /usr/include/readline/ ]; then
            echo "The development version of libreadline is installed -> copying"
            if [ `uname -p` = "x86_64" ]; then
                cp /lib64/libreadline.so.* "$SAGE_LOCAL"/lib
            else
                cp /lib/libreadline.so.* "$SAGE_LOCAL"/lib
            fi
            cp -r /usr/include/readline  "$SAGE_LOCAL"/include
            exit 0
        else
            echo "No headers found, building library."
            # # This variable is only set to "true" on openSUSE 11.1.                                     
            # OVERWRITE_READLINE="true"; export OVERWRITE_READLINE                                        
        fi
    fi
fi

Now tar the folder to get the spkg again and you are good to go.

Por guillem  |  en: mar 03 Ago 2010  |  0 Comentarios, Comentar...

Una ex charla que viene a cuento.

Python

Charla sobre Python en la Semana de la Ciencia 2009
Por guillem  |  en: mar 27 Jul 2010  |  2 Comentarios, Comentar...

Signals and slots

Python

One important aspect of adding a GUI to any code is that you must start thinking about events. Computations are easy from this point of view, either everything is serial or happens on a thread. With a GUI you must handle stuff like signals and slots.

Most of GUI libraries have some event handling primitives implemented, Qt uses signals and slots to connect events like pressing a button to a slot, that is, a function that is called when the event happens. I use Python to code GUIs so everything I'm saying from now on deals exclusively about Python.

A connection is a primitive that, needless to say, connects a signal to a slot. It has three arguments, the signal generator, the signal type and the slot. The slot is a function. More precisely a global function if you wan to avoid severe headaches trying to guess why your GUI is ignoring that function no matter how many times you press that button. There is a redundant question about this method. What can I do if I want to call a slot with arguments? A connection is between a signal and a function an there are no arguments present at any moment. I found an elegant solution this morning: use lambda functions in the connection calling. This will pre-eval the function with arguments and the connection won't see them.

Por guillem  |  en: mié 20 May 2009  |  2 Comentarios, Comentar...

El Creador nos habla en Python

Python

from os.path import walk,realpath,join                                                                                                                          
from os import system,chdir                                                                                  
from sys import argv          

def executeinkscape(format,dir,fnames):  
    for file in fnames:                                                                                                              
        if 'svg' in file:
            root = realpath('.')
            chdir(join(root,dir))
            system('inkscape %s --export-%s=%s'%(file,
                                                 format,
                                                 file.replace('svg',format))
                   )
            chdir(root)


if __name__ == '__main__':
    print "Convirtiendo figuras a %s \n"%(argv[1])
    walk('.',executeinkscape,argv[1])


Esta rutina hace lo siguiente. Si se le pasa el argumento 'formato' busca en el arbol de directorios a partir del directorio local todos los archivos que terminen con la extensión '.svg' y utiliza inkscape para exportarlos a 'formato' . Útil para no tener que guardar las figuras del libro en tres formatos distintos.

Por guillem  |  en: mié 22 Abr 2009  |  5 Comentarios, Comentar...

Pythonic unit conversion

Python

Unit conversion is one of the tasks in engineering computations that suck the most. It's just tedious and it is a source for million of stupid bugs. I'm writing software for a company and I was feeling the units pain so hard. I decided to face the problem and to build the ultimate unit conversion tool. And y pythonic one!

All the efforts I've found on the Internet define an intermediate class that emulates float. The obvious question is: if a measure is a float... Why not subclassing float? The answer is as easy as the fact that subclassing a built-in type in python is not that easy (what a sentence, my brain hurts). At least it reaches the proficient level in python that just a small portion of scientists have. All the fortran programmers (like me) get in serious trouble when deal with object orientation. Even more when the things get messy with class methods, instance methods, properties and decorators. I hardly understand classes and I've found that I didn't understand the python's new style classes at all (this is a problem given that in Python 3.0 there will only be new style classes).

The problem is the following. If you subclass float and define an instance method that returns self, as an instance method it does not return the derived class but the parent, in this case float. If we want the instance to behave like a factory of itself you must define a classmethod. The following code does the trick, all the explanations are in the documentation.

from constants import *

class Temperature(float):
    """
    Class that models a temperature measure with conversion utilities

    Supported units are

    * Kelvin

    * Celsius

    * Fahrenheit

    Normal instantiation is a temperature in Kelvin

    >>> T = Temperature(100)
    >>> T
    100.0

    But you can instantiate and specify if unit is Celsius or
    Fahrenheit

    >>> T = Temperature(100).unit('F')
    >>> T
    310.92777777777775

    Unit conversion is as easy as it gets.

    >>> T.C
    37.777777777777771
    >>> T.F
    99.999999999999986

    You can compute with temperatures because inherits from the float
    built-in

    >>> T1 = Temperature(200)
    >>> T2 = Temperature(0).unit('C')
    >>> T1+T2
    473.14999999999998

    If you don't want to use the class' attribute you can use the
    function `getattr` to get a value using the unit code.

    >>> getattr(T,'C')
    37.777777777777771
    """
    def __init__(self,data):
        float.__init__(self,float(data))
        self.data = float(data)

    @classmethod
    def factory(cls,data):
        """
        This factory makes that any returned value is a measure
        instead of a float.
        """
        return cls(data)

    def unit(self,units='K'):
        if units == 'K':
            return self.factory(self.data)
        elif units == 'C':
            return self.factory(C2K(self.data))
        elif units == 'F':
            return self.factory(F2K(self.data))
        else:
            raise ValueError("Wrong temperature input code")
        
    @property
    def C(self):
        return self.factory(K2C(self.data))

    @property
    def F(self):
        return self.factory(K2F(self.data))

This way is much faster because it avoids unnecessary method calls albeit being more pythonic.

Por guillem  |  en: vie 09 Ene 2009  |  0 Comentarios, Comentar...

Thermopy

Python

Como una de las cosas que hago son calderas pirotubulares he decidido juntar todos los módulos de cálculo en un pauqete llamado thermopy que puede descargarse del Python Package index. Tal como dice la documentación contiene lo siguiente:

  • Soporte completo para la base de datos de Alexander Burcat tanto para especies simples como para mezclas.
  • Cálculos de presiones y temperaturas de saturación así como entalpías siguiendo el actual estándar de IAPWS de agua, vapor y vapor sobrecalentado.
  • Modelo de combustor simple, que recibiendo un reductor cualquiera y un exceso de aire (o razón de equivalencia) proporciona la composición de gases resultado, la entalpía de combustión y la temperatura de combustión adiabática.
  • Modelo de aire húmedo que, dada cualquier mezcla de gases que contenga agua, proporciona la humedad relativa y la temperatura de rocío.

Estoy preparando la documentación, pero me llevará un tiempo. Para instalarlo, si disponéis de python y setuptools instalado, bastará con un

easy_install -U thermopy
 y automáticamente instalará todas las dependencias necesarias.  Que lo disfrutéis.

Por guillem  |  en: dom 04 Ene 2009  |  0 Comentarios, Comentar...
Página siguiente