Friday, June 27, 2008

C++ templates: an introduction

Have you ever needed to have multiple versions of the same function, with the only difference being the date type used for the arguments and/or value returned? For example, you might need versions of the same function that work with int, float and double data types. The most obvious way to do this is to use overloading, and explicitly define the required functions, all with the same name and content except for the data type.

An alternative is to use a template. This allows you to determine a function with a generic data type. For example:

template <class T>
T SumArray(T *array, int num)
{
   T my_sum = 0;
   for (int i=0; i<num; i++)
   {
      my_sum += array[i];
   }
   return(my_sum);
}


This is a very simple function that sums the first num values in an array. To use this for an integer array:

int arr[10];
int value = SumArray<int>(arr, 10);

Or you use it for doubles:

double arr[15];
double value = SumArray<double>(arr, 15);

This of course can be trivially extended to multiple data types, for example:

template <class T, class U>
double SumTwoArrays(T *array1, U *array2, int num1,
                    int num2)
{
   double my_sum = 0;
   for (int i=0; i<num1; i++)
   {
      my_sum += array1[i];
   }
   for (int i=0; i<num2; i++)
   {
      my_sum += array2[i];
   }
   return(my_sum);
}

Here a double is always returned by the function, but it has two input arguments, which can be of different types.

Saturday, June 21, 2008

Fast Artificial Neural Network Library

The Fast Artificial Neural Network Library (FANN) is a good way to get started with neural networks.

Fast Artificial Neural Network Library is a free open source neural network library, which implements multilayer artificial neural networks in C.

The web page is here. The documentation contains some simple example which illustrate how to train and test a neural network. Cascade training is a useful feature, where neurons are added during training, which means that users don't need to determine how many neurons and hidden layers should be in the network before training.

Importing data into MySQL

Rather than using a Perl script, for example, data can be imported directly into MySQL using LOAD DATA LOCAL INFILE. Note that if you don't include LOCAL, the file you want to import must be located on the server, rather than a client.

For example, suppose you have an ASCII file containing comma-delimited data that you want to insert into the table my_table. Type:

LOAD DATA LOCAL INFILE 'data.txt'
INTO TABLE my_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, field2, field3, field4, field5);


Here we have specified that the data is comma-delimited, and each line of the input file corresponds to a row in the table. The columns that each piece of data should be inserted into are also specified.

MySQL can read only the lines in a data file containing a specified prefix if necessary. For example, if each line with real data begins with DATA_ENTRY, and you want to ignore all others, add:

LINES STARTING BY 'DATA_ENTRY'


MySQL will skip the prefix, and anything that comes before it. Lines not including the prefix will be completely skipped.

Monday, June 2, 2008

Qt example : generating a single QImage in a separate thread to the GUI

Here we consider the situation when a GUI-driven application needs to generate a QImage, however, due to the time required to generate the QImage, the GUI would freeze unless the QImage is generated in a separate thread. This example is similar to the Mandelbrot example code in the Qt documentation, however the code presented here is much simpler and easier to follow.

It is important to remember that while a QImage can be made outside the GUI thread, this cannot be done for QPixmaps or QWidgets, for example (QPixmaps and QWidgets can only be used in the GUI thread).

The example consists of the following files: main.C, window.C, window.h, thread.C, thread.h, imagewindow.C and imagewindow.h.

main.C

#include <QApplication>
#include "window.h"

//----------------------------------------------------------------------------
//
// main program
//
//----------------------------------------------------------------------------

int main (int argc, char **argv)
{
QApplication app(argc, argv);
Window window;
window.show();
window.setMaximumSize(window.minimumWidth(),
window.minimumHeight());
return app.exec();
}


window.C

Here we make a simple GUI containing just a single button. When the button is clicked, an abstract image is generated in another thread when QThread::start() is called. Using Qt's signals and slots, when the image has been generated, it is sent to the GUI thread and then displayed on the screen.
#include "window.h"

//----------------------------------------------------------------------------
//
// the main GUI
//
//----------------------------------------------------------------------------

//------------
// constructor
//------------

Window::Window(QWidget *parent) : QWidget(parent)
{
setWindowTitle("Qt example 02");
runButton = new QPushButton("Generate image...");
connect(runButton, SIGNAL(clicked()),
this, SLOT(run_thread()));

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(runButton);
setLayout(layout);

// window to display the image

imageWindow = new ImageWindow();

// the QImage generation thread

qRegisterMetaType<QImage>("QImage");
otherThread = new timeConsumingThread();

// slot to respond to the QImage generation thread
// - display the image in a window

connect(otherThread, SIGNAL(theImage(const QImage &)),
this, SLOT(displayImage(const QImage &)));
}

//--------------------
// slot to run thread
//-------------------

void Window::run_thread()
{
if (!otherThread->isRunning())
{
otherThread->start();
}
}

//-------------------
// display the QImage
//-------------------

void Window::displayImage(const QImage &image)
{
imageWindow->plot = QPixmap::fromImage(image);
imageWindow->show();
imageWindow->update();
imageWindow->raise();
imageWindow->activateWindow();
}


window.h

#ifndef WINDOW_H_
#define WINDOW_H_

#include <QPushButton>
#include <QThread>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QMetaType>

#include "thread.h"
#include "imagewindow.h"

class Window : public QWidget
{
Q_OBJECT

public:
Window(QWidget *parent = 0);

private:
QPushButton *runButton;
timeConsumingThread *otherThread;
ImageWindow *imageWindow;

public slots:
void run_thread();
void displayImage(const QImage &);
};

#endif /*WINDOW_H_*/


thread.C

Here we have the time-consuming image generation in the run() reimplementation. In this example, the rendering of the image doesn't actually take too long and is just a very simple abstract image. After the image has been generated, we emit a signal containing the image.
#include "thread.h"

//----------------------------------------------------------------------------
//
// thread which runs the time-consuming image generation
//
//----------------------------------------------------------------------------

//------------
// constructor
//------------

timeConsumingThread::timeConsumingThread(QObject *parent)
: QThread(parent)
{

}

//-----------------------
// run - paint the QImage
//-----------------------

void timeConsumingThread::run()
{
QImage myQImage(600, 600, QImage::Format_RGB32);
QPainter painter(&myQImage);
for (int i=0; i<600; i++)
{
for (int j=0; j<600; j++)
{
double hue = (double)(i + j + i*j)/361200.0;
QColor myColor;
myColor.setHsvF(hue, 1.0, 1.0, 1.0);
painter.setPen(myColor);
painter.drawPoint(i, j);
}
}
emit theImage(myQImage);
}


thread.h
#ifndef THREAD_H_
#define THREAD_H_

#include <QThread>
#include <QImage>
#include <QColor>
#include <QPainter>

class timeConsumingThread : public QThread
{
Q_OBJECT

public:
timeConsumingThread(QObject *parent = 0);

signals:
void theImage(const QImage &);

protected:
void run();

};

#endif /*THREAD_H_*/


imagewindow.C

Here we setup a simple window which is used for displaying the image. In paintEvent() we draw the QPixmap containing our image onto the window.
#include "imagewindow.h"

//----------------------------------------------------------------------------
//
// image window
//
//----------------------------------------------------------------------------

//------------
// constructor
//------------

ImageWindow::ImageWindow(QWidget *parent) : QWidget(parent)
{
setFixedSize(600, 600);
setWindowTitle("Qt Example 02: Image");
}

//-----------------------------------------------------------------------------
//
// paint the image
//
//-----------------------------------------------------------------------------

void ImageWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.drawPixmap(0, 0, plot);
}


imagewindow.h

#ifndef IMAGEWINDOW_H_
#define IMAGEWINDOW_H_

#include <QWidget>
#include <QPixmap>
#include <QPainter>

class ImageWindow : public QWidget
{
Q_OBJECT

public:
ImageWindow(QWidget *parent = 0);
QPixmap plot;

private:

protected:
void paintEvent(QPaintEvent *event);

};

#endif /*IMAGEWINDOW_H_*/
This example can be compiled by the following:

qmake -project
qmake
make

Sunday, June 1, 2008

Natural Docs

I came across Natural Docs recently.

Natural Docs is an open-source documentation generator for multiple programming languages. You document your code in a natural syntax that reads like plain English. Natural Docs then scans your code and builds high-quality HTML documentation from it.


Natural Docs is trivial to install, and it's very easy and quick to get started. The natural syntax used by Natural Docs is so natural it's almost possible that you could accidently have comments in your code already in the required syntax :-)

Qt: simple example of use of QtConcurrent

In this example we assume that a function my_func takes a long time to run, and would cause the GUI to freeze if it were run in the main GUI thread. In order to avoid the GUI freezing, we run my_func in a separate thread. The GUI will be therefore be fully functional while my_func is running.

When this application launched, a small GUI will appear containing a single button. When the button is clicked, the function my_func is run in a separate thread. When the thread finishes running, a message appears on the screen.

This example makes uses QtConcurrent::run(), QFuture and QFutureWatcher, rather than just a QThread. Qt 4.4.0 or above is required.

This example consists of the following codes: main.C, user_def.h, window.C and window.h.

main.C

Here we define the time-consuming operation. In this example, it is just a summation.
#include <QApplication>

#include "window.h"
#include "user_def.h"

//----------------------------------------------------------------------------
//
// the user's time-consuming function
//
//----------------------------------------------------------------------------

void my_func(void)
{
// time-consuming code
double sum;
for (int i=0; i<100000; i++)
{
for (int j=0; j<100000; j++)
{
sum = sum * i / j;
}
}
}

//----------------------------------------------------------------------------
//
// main program
//
//----------------------------------------------------------------------------

int main (int argc, char **argv)
{
QApplication app(argc, argv);
Window window;
window.show();
window.setMaximumSize(window.minimumWidth(),
window.minimumHeight());
return app.exec();
}


user_def.h
#ifndef USER_DEF_H_
#define USER_DEF_H_

void my_func(void);

#endif /*USER_DEF_H_*/


window.C

Here we setup a very simple GUI just containing a single button. When the button is clicked, the time-consuming operation my_func is run in another thread when QtConcurrent::run() is called. We use a QFutureWatcher to monitor the state of the other thread. When the GUI thread receives a signal from the QFutureWatcher that the function has finished running, it displays a message on the screen using a QMessageBox.

#include "window.h"

//----------------------------------------------------------------------------
//
// the main GUI
//
//----------------------------------------------------------------------------

//------------
// constructor
//------------

Window::Window(QWidget *parent) : QWidget(parent)
{
setWindowTitle("Qt example 03");
runButton = new QPushButton("Run the function...");
connect(runButton, SIGNAL(clicked()),
this, SLOT(run_thread()));

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(runButton);
setLayout(layout);

// create a QFuture and a QFutureWatcher

future = new QFuture<void>;
watcher = new QFutureWatcher<void>;

// display a message box when the calculation has finished

connect(watcher, SIGNAL(finished()),
this, SLOT(displayFinishedBox()));

}

//-----
// slot
//-----

void Window::run_thread()
{
*future = QtConcurrent::run(my_func);
watcher->setFuture(*future);
}

//----------------
// display message
//----------------

void Window::displayFinishedBox()
{
QMessageBox::information(this, tr("Qt Example 03"),
tr("The function my_func has finished."));
}


window.h
#ifndef WINDOW_H_
#define WINDOW_H_

#include <QPushButton>
#include <QThread>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QtConcurrentRun>
#include <QFuture>
#include <QFutureWatcher>

#include "user_def.h"

class Window : public QWidget
{
Q_OBJECT

public:
Window(QWidget *parent = 0);

private:
QPushButton *runButton;
QFuture<void> *future;
QFutureWatcher<void> *watcher;

public slots:
void run_thread();
void displayFinishedBox();
};

#endif /*WINDOW_H_*/


This example can be compiled easily using:

qmake -project
qmake
make