Wednesday, February 29, 2012

ETIS en la UOC: Nuevo semestre

Hoy empieza un nuevo semestre en la UOC.
Me matriculé de las siguientes asignaturas:
  1. Ampliació d'estructura i tecnologia de computadors
    Es la continuación de Estructura i tecnologia de computadors que hice el semestre anterior. Por lo poco que he visto parece que, aún teniendo menos créditos, me llevará mucho más tiempo que ETC.
  2. Matemàtica discreta
    Esta es la que tuve que dejar el semestre anterior. A ver si esta vez lo consigo.
  3. Teoria d'autòmats i llenguatges formals I
    Esta la cogí porque me entró la curiosidad después de oir decir que es una asignatura muy bonita a varios compañeros de trabajo que son ingenieros informáticos. Espero que me guste a mi también.
En cuanto al calendario de entregas, este semestre no están tan repartidas como el pasado. Hay dos puntos del semestre (a mitad de Abril y a final de Mayo) en los que en 8 días tendré que hacer 4 entregas.
Parece que tendré que organizarme mejor que el semestre pasado y empezar las PACs y prácticas con más antelación.
Ya contaré por aquí como fue todo.

Saturday, February 25, 2012

Revisiting Wrapping a boost random uniform generator in a class.

In a previous post we commented how we had wrapped a boost random generator in a class. This is the code of the class we wrote:
#ifndef RANDOMNUMBERGENERATOR_H_
#define RANDOMNUMBERGENERATOR_H_

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>

template <int seed>
class RandomNumberGenerator {
  public:
    RandomNumberGenerator() {};
    virtual ~RandomNumberGenerator() {};

    double operator() () {
     static boost::mt19937 generator(seed);
     static boost::uniform_01<boost::mt19937> 
                               distribution(generator);
     return distribution();
    }
};
#endif /* RANDOMNUMBERGENERATOR_H_ */
Well, it turned out that this version is wrong if you want to use more than one random generator in your simulation.
We found it out the hard way as we added more tests before adding new features to the class. We didn’t get what we were expecting. After printing out 50 or so random numbers generated using a given seed, we realized that the problem was that the RandomNumberGenerator objects we were using in different tests were not independent.

At work I started a C++ reading club some time ago. This last week we have been reading the Thinking in C++ chapter about name control. There we found out why we were getting a wrong behaviour:

The static objects inside a function (in our code the operator()) are initialized only once, i.e. the first time the function is called. However destructors for static objects are called when main() exits or when the Standard C library function exit() is called.

Therefore, no matter how many new RandomNumberGenerator objects with different seeds we tried to create, they all had the same distribution object than the first one and so the random number sequence, instead of starting again from the begginning for each test as we expected, contained the random numbers that followed the ones we got in the previous test.

Since we want to use more than one random number generator in our simulation, we cannot use the code showed before. We are now using a code that is very similar to the first version showed in a previous post, but avoiding dynamic memory (thanks to another thing we've learned in Thinking in C++ chapter 14).

This is the new code (with some new features) which is passing all the tests:
#ifndef RANDOMNUMBERGENERATOR_H_
#define RANDOMNUMBERGENERATOR_H_

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>

class RandomNumberGenerator
{
  public:
    RandomNumberGenerator(int seed) 
    : generator(seed), distribution(generator) {};

    virtual ~RandomNumberGenerator(){};

    double operator() () {
      return distribution();
    }

    double operator() (double lowerLimit, double upperLimit) {
      double width = upperLimit - lowerLimit;
      return width * (*this)() + lowerLimit;
    }

  private:
    boost::mt19937 generator;
    boost::uniform_01<boost::mt19937> distribution;
};
#endif /* RANDOMNUMBERGENERATOR_H_ */
These are the tests:
#include <CppUTest/TestHarness.h>
#include "../Math/RandomNumberGenerator.h"
#include "Constants.h"
#include <iostream>
#include <iomanip>

using namespace std;

static double randomSequence[] = 
 {0.8701241324,0.6960659768,0.5822769315,0.43324903,0.2788389467,
  0.09882423049,0.185911238,0.1808245534,0.4111001296,0.1506180582,
  0.117375552,0.2591784317,0.6849687463,0.6209091851,0.4376110642,
  0.1751907461,0.5562293304,0.2715550633,0.3670803171,0.7612549367,
  0.4023657234,0.9465064413,0.1130407061,0.01872990816,0.447030843,
  0.5319397049,0.5854451165,0.4068064995,0.1619850995,0.6079116813,
  0.5207187904,0.6593447439,0.3260511269,0.3620603553,0.6991862394,
  0.3057702733,0.3663945452,0.9071284649,0.8363745112,0.2565871561,
  0.4813429436,0.2315147296,0.5165022933,0.9432465574,0.3830481281,
  0.4775455245,0.9975408914,0.6317734621,0.5142444882,0.8496764714,
  0.5590532762,0.3113280749,0.03444976453,0.6056593289,0.7199300299,
  0.4580037531,0.4210035447,0.639783914,0.4369351231,0.8001209884,
  0.2817007573,0.1494443719,0.9002743375,0.230675949,0.6696122757,
  0.6084528021,0.4560687505,0.5023682739,0.2898043399,0.7198582094,
  0.5258189649,0.6155499958,0.5592420595,0.8967758908,0.7452838295,
  0.6167110542,0.8283462557,0.1519206658,0.8236944464,0.9035853394,
  0.07714032172,0.4713783977,0.6448620677,0.9572030935,0.3092575835,
  0.5109028067,0.5242537172,0.6404849922,0.9580923351,0.7580416379,
  0.8832009526,0.6661859956,0.2954318929,0.07275792654,0.512375993,
  0.05308085051,0.08870241721,0.9696914584,0.6417167294,0.6661955242};

TEST_GROUP(TestRandomNumberGenerator) {
};

TEST(TestRandomNumberGenerator, 
        GetRandomNumbersBetween_0_1) {
  RandomNumberGenerator gen(25);
  for (int i=0; i<100; ++i) {
    double r = gen();
    CHECK( (r < 1.0) and (r >= 0.0) );
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeed) {
  RandomNumberGenerator gen(25);
  for (int i=0; i<100; ++i) {
    DOUBLES_EQUAL(randomSequence[i], gen(), PRECISION);
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeedAndIterval_0_1) {
  RandomNumberGenerator gen(25);
  for (int i=0; i<100; ++i) {
    DOUBLES_EQUAL(randomSequence[i], gen(0, 1), PRECISION);
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeedAndIterval_0_5) {
  RandomNumberGenerator gen(25);
  for (int i=0; i<100; ++i) {
    DOUBLES_EQUAL(randomSequence[i] * 5., gen(0, 5), PRECISION);
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeedAndIterval_1_5) {
  RandomNumberGenerator gen(25);
  for (int i=0; i<100; ++i) {
    DOUBLES_EQUAL(randomSequence[i] * 4. + 1., gen(1, 5), PRECISION);
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeedAndIterval_1_2) {
  RandomNumberGenerator gen(25);
  for (int i=0; i<100; ++i) {
    DOUBLES_EQUAL(randomSequence[i] * 1. + 1., gen(1, 2), PRECISION);
  }
}
As we said in the previous post about this topic, we still have so much to learn...

Thursday, February 23, 2012

How to install Boost C++ libraries in Ubuntu and use them in Eclipse CDT

Boost is one of the most popular C++ development libraries. If you want to use them in your C++ project in Eclipse CDT in an Ubuntu environment, follow these instructions:

Installing the package
In the last Ubuntu releases, boost libraries have been split in different packages. The fastest option is to install the whole library:
$ sudo apt-get install libboost-dev
Adding the library in Eclipse CDT
Right click into your C++ project, select "Properties". Go to "C/C++ Build" options and here select "Settings". In the "GCC C++ Compiler" subsection, select "Includes" and add in the "Includes files (-include)" field, try to include any of the Boost C++ headers.
In our case we wanted to use the random numbers libraries, so we included the header file: "/usr/include/boost/random.hpp". After having done this, click on Apply.
You'll probably need to "Clean" your project before everything compiles again.

Once you've finished the settings, try to include any of the Boost sub-libraries, for example creating a new C++ class and including the following lines:
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>
If there is no problem at compiling nor linking, Boost C++ libraries are ready to be used in your machine.

Update
These setting instructions are fine for Eclipse Indigo.
For Eclipse Helios, though, one of the steps is different:
- To include the Boost C++ header you need to go to "GCC C Compiler" subsection instead of "GCC C++ Compiler" .

Saturday, February 18, 2012

Articles and Posts read

Inspiring and Interesting
"Te sangran los dedos y disfrutas del sufrimiento"
Last of the Cave People by Mark Jenkins National Geographic
Mix, Match, Morph. How to Build a Dog by Evan Ratliff National Geographic

Learning and Software Craftsmanship
How much practice is too much?
Aging brains don't necessarily fade - they adapt
Seven things highly productive people do
Be the worst
How Employers Can Help Solve the Skills Gap
Enhance Metacognition and Problem-Solving by Talking Out Loud to Yourself
Discipline in Software Development and in Life
The aim of architecture
Do not comment. Assert it!
Osmius: Evaluación Final
The programming assembly-line

C++ 
No BS, from BS
Accessing Configuration Data
Watch Out For Multipletons
Start Big?
C++ Dudes To Follow
The Language Of The Language
Fully Qualified

Agile and Lean
El MVP es un experimento, no una chapuza

Spain and Europe 
Hagamos un caldo con la gallina de los huevos de oro 
Cómo ayudar y no estorbar a la ola de emprendedores
Queridos Españoles, ¡no os equivoquéis de batalla!
Reforma Laboral
Atrapados en el norte
The Battle For Spanish Society
Upside Down and Inside Out Thinking – The Battle For Spanish Society Part Three
Crear una empresa en 3 horas por 71 euros
¿Qué implica abrir una empresa en Londres?
Sin el Hartz IV el índice de paro en Alemania superaría el 15%.

Wednesday, February 15, 2012

Wrapping a boost random uniform generator in a class.

@irrati0nal and I decided to use Boost.Random as the random generator library in our pet project.
We wanted to wrap it in a class so we could avoid using it directly in our code. This way it would be easier to change to a different random library if we decided to do it. It was our first experience using the boost libraries. Since we don’t understand templates very well yet, we suffered a bit to get our random generator class working.
We checked the boost documentation example, Bojan Nikolic's examples and some answers in Stack Overflow like this one, but we still didn’t know how to do it. So we decided to hack a solution based on the Stack Overflow answer and Nikolic's examples.
After struggling for a while we finally got to a clumsy solution that compiled and passed the tests:
#ifndef RANDOMNUMBERGENERATOR_H_
#define RANDOMNUMBERGENERATOR_H_

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>

class RandomNumberGenerator {
  public:
    RandomNumberGenerator(int seed) {
     generator = new boost::mt19937(seed);
     distribution = 
          new boost::uniform_01<boost::mt19937>(*generator);
    };

    virtual ~RandomNumberGenerator() {
     delete generator;
     delete distribution;
    };

    double operator() () {
     return (*distribution)();
    }

  private:
    boost::mt19937 *generator;
    boost::uniform_01<boost::mt19937> *distribution;
};
#endif /* RANDOMNUMBERGENERATOR_H_ */
#include <CppUTest/TestHarness.h>
#include "../Math/RandomNumberGenerator.h"
#include <iostream>
#include <iomanip>

using namespace std;

const double PRECISION = 1.0e-8;
static const int seed = 25;
static RandomNumberGenerator gen(seed);

TEST_GROUP(TestRandomNumberGenerator) {
};

TEST(TestRandomNumberGenerator, 
        GetRandomNumbersBetween01) {
  for (int i=0;i<100;++i) {
    double r = gen();
    CHECK( (r < 1.0) and (r >= 0.0) );
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeed) {
  double a[] = {0.8701241323724389,
  0.6960659767501056,
  0.5822769314981997,
  0.4332490300294012,
  0.2788389467168599};

  for (int i=0;i<5;++i) {
   DOUBLES_EQUAL(a[i], gen(), PRECISION);
  }
}
Then we decided to try if we could refine the code to use templates and avoid using dynamic memory, and this was the result:
#ifndef RANDOMNUMBERGENERATOR_H_
#define RANDOMNUMBERGENERATOR_H_

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>

template <int seed>
class RandomNumberGenerator {
  public:
    RandomNumberGenerator() {};
    virtual ~RandomNumberGenerator() {};

    double operator() () {
     static boost::mt19937 generator(seed);
     static boost::uniform_01<boost::mt19937> 
                               distribution(generator);
     return distribution();
    }
};
#endif /* RANDOMNUMBERGENERATOR_H_ */
#include <CppUTest/TestHarness.h>
#include "../Math/RandomNumberGenerator.h"
#include <iostream>
#include <iomanip>

using namespace std;

const double PRECISION = 1.0e-8;
static const int seed = 25;
static RandomNumberGenerator<seed> gen;

TEST_GROUP(TestRandomNumberGenerator) {
};

TEST(TestRandomNumberGenerator, 
        GetRandomNumbersBetween01) {
  for (int i=0;i<100;++i) {
    double r = gen();
    CHECK( (r < 1.0) and (r >= 0.0) );
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeed) {
  double a[] = {0.8701241323724389,
  0.6960659767501056,
  0.5822769314981997,
  0.4332490300294012,
  0.2788389467168599};

  for (int i=0;i<5;++i) {
   DOUBLES_EQUAL(a[i], gen(), PRECISION);
  }
}
We were really excited with our little success so we tried to push the template solution a bit further and got to this:
#ifndef RANDOMNUMBERGENERATOR_H_
#define RANDOMNUMBERGENERATOR_H_

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>

template <int seed, class rng, class distrib>
class RandomNumberGenerator {
  public:
    RandomNumberGenerator() {};
    virtual ~RandomNumberGenerator() {};

    double operator() () {
     static rng generator(seed);
     static distrib distribution(generator);
     return distribution();
    }
};
#endif /* RANDOMNUMBERGENERATOR_H_ */
#include <CppUTest/TestHarness.h>
#include "../Math/RandomNumberGenerator.h"
#include <iostream>
#include <iomanip>

using namespace std;

const double PRECISION = 1.0e-8;
static const int seed = 25;
static RandomNumberGenerator<seed, 
                     boost::mt19937, 
                     boost::uniform_01<boost::mt19937> > gen;

TEST_GROUP(TestRandomNumberGenerator) {
};

TEST(TestRandomNumberGenerator, 
        GetRandomNumbersBetween01) {
  for (int i=0;i<100;++i) {
    double r = gen();
    CHECK( (r < 1.0) and (r >= 0.0) );
  }
}

TEST(TestRandomNumberGenerator, 
        GetRandomNumberSequenceWithGivenSeed) {
  double a[] = {0.8701241323724389,
  0.6960659767501056,
  0.5822769314981997,
  0.4332490300294012,
  0.2788389467168599};

  for (int i=0;i<5;++i) {
   DOUBLES_EQUAL(a[i], gen(), PRECISION);
  }
}
It also worked but we realized that we didn’t understand very well what was going on, and that the declaration of the generator had become much more complicated.
Since we were not going to be using different random generators or statistical distributions, we decided to keep it simple and stick to the second solution which is easier to understand (for us) and also makes the generator creation easier.
Besides having a lot of fun, we’ve realized how little C++ we know and that we are eager to learn more about templates and the boost library.

PS: By the way we are using a Mersenne Twister: "Mersenne Twister: A 623-dimensionally equidistributed uniform pseudo-random number generator", Makoto Matsumoto and Takuji Nishimura, ACM Transactions on Modeling and Computer Simulation: Special Issue on Uniform Random Number Generation, Vol. 8, No. 1, January 1998, pp. 3-30. 
I talked about another version of this generator in a previous post.

Update
There is an update of this post: Revisiting Wrapping a boost random uniform generator in a class.

Sunday, February 12, 2012

Interesting Talk: "C++11 Style"

Great keynote in Going Native 2012:

Streamlines with Matplotlib

This is a translation into English of an old post in Spanish.

As an assignment for the Numerical Methods for Dissipative Systems course I had to solve the 2D Laplace equation in a rectangle with some given boundary conditions.
I wrote a program to solve it in C, but to do the streamline graphics I used MatPlotLib.
This is the Python script that generated the streamlines:
# -*- coding: iso-8859-15
import sys
from numpy import * 
from pylab import load  
import matplotlib.pyplot as plt
if len(sys.argv) >= 1:
    psi = load(sys.argv[1])
    cs = plt.contour(psi,20)
    plt.clabel(cs)
    plt.xlabel("y/h")
    plt.ylabel("x/h")
    plt.show()
else:
    print "This program needs the path to the file that contains the psi matrix"

To generate the streamlines we should execute the script passing to it the path of the file where the solution matrix is. In this case the entries of the matrix must be separated by white spaces. Reading the help of the load function, you can learn how to modify it to use different delimiters.

I run the script from iPython:
$ ipython
Python 2.5.2 (r252:60911, Dic 20 2009, 23:16:55) 
Type "copyright", "credits" or "license" for more information.

IPython 0.8.4 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: run ~/grafico.py 'pathToFileWithSolutionMatrix'
and this was the result:

To be able to run it, besides python, you'll need to install the following modules: numpy, pylab and matPlotLib (you can find them all in the Ubuntu repositories).

Saturday, February 11, 2012

ETIS en la UOC: Asignaturas del pasado semestre

Últimamente no he publicado ningún post porque hasta hace muy poco he estado liado con los exámenes de las asignaturas que matriculé en la UOC
Bueno, al final no me ha ido del todo mal. Tuve que dejar una de las asignaturas, Matemàtica Discreta (6 créditos), porque no me daba tiempo de trabajar y llevar las tres asignaturas al mismo tiempo, pero saqué Matrícula de Honor en las dos asignaturas con las que decidí continuar, Estructura de la Informació y Estrucutura i Tecnología de Computadors, (6+9= 15 créditos). 
Esto último es genial porque la UOC es muy cara, y las dos MH me compensan lo que pagué por la asignatura que tuve que dejar y harán que la próxima matrícula me salga un poco más barata. También he aprendido donde está mi límite: 15 créditos por semestre.

Estas son mis impresiones sobre las dos asignaturas que terminé:

Estructura de la Informació
Me gustó mucho. Aprendí sobre distintas estructuras de datos, su eficiencia, implementación y aplicación. También aprendí algoritmos que no conocía, y sobre complejidad, notación O y todo eso. En otras asignaturas, y por mi cuenta, ya había visto algunas estructuras de datos simples (vectores, listas encadenadas, colas y pilas), pero en esta asignatura además de profundizar en ellas, trabajé con otras que no había usado antes, como colas con prioridad, heaps, árboles, tablas de dispersión y árboles de búsqueda.
En cuanto a la parte práctica de la asignatura, aprendí a usar y crear clases genéricas en Java, y utilicé TDD en el desarrollo de todas las prácticas. Esto último no era necesario, pero decidí que las prácticas por su tamaño, nivel de complejidad y límite de tiempo, podrían servirme como un breakable toy ideal con el que practicar TDD. Este es el código resultante. Si uno sabe defenderse con Java, las prácticas de esta asignatura se pueden hacer sin pasar demasiados apuros.

Estructura i tecnologia de computadors. Esta se me hizo un poco más dura por su extensión (9 créditos) y por la cantidad de trabajo que acarreaba: 4 Proves d'Avaluació Continuada (PACs) y una Pràctica Final.
La mayoría del temario no era nuevo para mi, ya que había hecho una asignatura en Física con contenidos parecidos: Fonaments de Conmutació.
Sin embargo, el enfoque del temario era diferente, porque la asignatura de física daba más importancia a la parte electrónica (se ven más tipos de biestables, más tipos de autómatas, se hacen prácticas en el entorno Quartus II de ALTERA, etc.), mientras que la asignatura de ETIS daba más importancia a los conceptos que son útiles para explicar cómo funciona un ordenador. Por este motivo se hacía más hincapié en la representación numérica de la información, se explicaba los circuitos combinacionales y secuenciales sin entrar en tanto detalle como en la asignatura de física, y finalmente se dedicaba mucho tiempo a describir el funcionamiento de un ordenador sencillo: la máquina rudimentaria (MR).
Este último tema dedicado a la MR es el más importante de la asignatura, ya que la última PAC, la Práctica, y un 40% del examen final se centran exclusivamente en él. De todas formas para entenderlo se necesita haber comprendido bien todos los temas anteriores.
Es una asignatura que da mucho trabajo, pero al final le acabas cogiendo el gusto a “hacer de ordenador”, y entiendes cómo se decodifican y ejecutan las instrucciones de ensamblador. Hacer las PACs te ayuda muchísimo para prepararte para la Práctica y el examen final.
Tengo que darle las gracias a los compañeros que encontre en CAUOC con los que tuve oportunidad de discutir dudas, contrastar resultados y preparar el examen. También me ayudaron mucho en algún momento de desanimo. Muchas gracias a todos, especialmente a juanvmtz y a Lennon.
No sé si me servirá de algo algún día, pero al menos fue un buen sudoku para mantener mi mente activa.