Showing posts with label Cpp. Show all posts
Showing posts with label Cpp. Show all posts

Wednesday, June 28, 2017

C++ implementation for Linear Genetic Programming

cpp-linear-genetic-programming


Package provides C++ implementation of linear genetic programming algorithms described in the book "Linear Genetic Programming".

Introduction

Linear Genetic Programming examines the evolution of imperative computer programs written as linear sequences of instructions. In contrast to functional expressions or syntax trees used in traditional Genetic Programming (GP), Linear Genetic Programming (LGP) employs a linear program structure as genetic material whose primary characteristics are exploited to achieve acceleration of both execution time and evolutionary progress (From the book "Linear Genetic Programming").

Usage

git clone this project to your local computer. The solution file can be open and run using Visual Studio IDE 2017.
Please refers one of the following folders (each of which solve a different optimization problem) on how to create the set of source files that will solve your problem:
  • mexican_hat
  • spiral_classification
  • symreg
The main code to run in the main looks like the following (Note that the C++ code uses xml files for configuration), you can test run the codes in the main.cpp file.
void mexican_hat_demo()
{
 LGPConfig config("mexican_hat\\LGPConfig.xml");
 std::cout << config.ToString() << std::endl;

 mexican_hat::XPop  pop(&config);
 //LGPStats stats(&pop);

 pop.BreedInitialPopulation();

 while(!pop.Terminated())
 {
  pop.Evolve();
  std::cout << "mexican hat generation: " << pop.GetCurrentGeneration() << std::endl;
  std::cout << "global fitness: " << pop.GetGlobalFittestProgram()->GetFitness() << "\tcurrent fitness: " << pop.GetFittestProgram()->GetFitness() << std::endl;
  //stats.LogStatistics();
 }

 std::cout << pop.GetGlobalFittestProgram()->ToString(true) << std::endl;
}

Monday, July 22, 2013

Return the filename from the full file path in MFC

Below is the code snippet for a C++ function to return the filename from the full file path in MFC:

#include "StdAfx.h"

CString CAppUtilManager::ExtractName(CString strFullPath) const
{
 int pos=strFullPath.ReverseFind('\\');
 return strFullPath.Right(strFullPath.GetLength()-pos-1);
}

Return the list of files from a directory in MFC

Below is the code snippet that implements a C++ function to return the list of files in a directory in MFC:


#include "StdAfx.h"

void CAppUtilManager::GetFiles(const CString& parent_folder, const CString& filters, CStringArray& files, BOOL bRecursive) const
{
 CFileFind fFind;
 BOOL bWorking=fFind.FindFile(parent_folder+_T("\\")+filters);

 while(bWorking==TRUE)
 {
  bWorking=fFind.FindNextFile();
  if(fFind.IsDots())
  {
   continue;
  }
  if(fFind.IsDirectory())
  {
   if(bRecursive==TRUE)
   {
    GetFiles(fFind.GetFilePath(), filters, files, bRecursive);
   }
  }
  else
  {
   files.Add(fFind.GetFilePath());
  }
 }
 fFind.Close();
}

Return the list of sub folders from a directory in MFC

Below is the code snippet for a C++ function to return a list of sub folders from a directory in MFC:

#include "StdAfx.h"

void CAppUtilManager::GetSubFolders(const CString& parent_folder, CStringArray& sub_folders) const
{
 CFileFind fFind;
 BOOL bWorking=fFind.FindFile(parent_folder+_T("\\*.*"));

 while(bWorking==TRUE)
 {
  bWorking=fFind.FindNextFile();
  if(fFind.IsDots())
  {
   continue;
  }
  if(fFind.IsDirectory())
  {
   sub_folders.Add(fFind.GetFilePath());
  }
 }
 fFind.Close();
}

Open a Folder Browser with Create Button in MFC

Below is the code snippet that implements a C++ function to open a folder browser in MFC with a Create Folder button, and return the path to the selected folder.


#include "StdAfx.h"
#include "shlobj.h"

CString CAppUtilManager::BrowseForDirectory() const
{
 int MAX_PATH=256;
 TCHAR display_name[MAX_PATH];
 TCHAR path[MAX_PATH];
    BROWSEINFO bi = { 0 };
    bi.lpszTitle = _T("Select an existing or created folder");
 bi.pszDisplayName=display_name;
 bi.ulFlags |= BIF_NEWDIALOGSTYLE;
    LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

 CString directory_path(_T(""));

    if(pidl != 0)
    {
        // get the name of the folder and put it in path
        SHGetPathFromIDList (pidl, path);

        //Set the current directory to path
        directory_path=path;

        // free memory used
        IMalloc * imalloc = 0;
        if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
        {
            imalloc->Free ( pidl );
            imalloc->Release ( );
        }
    }

 return directory_path;
}

Having TinyXML working with MFC

If you are using TinyXml with MFC, remember to add the following line

#include "stdafx.h"

to the top of the the source files tinystr.cpp, tinyxml.cpp, and tinyxmlerror.cpp, tinyxmlparser.cpp to prevent compilation error in MFC project.

Performing Statistical Hypothesis Test in C++ using AlgLilb: Student's t-test and Wilcoxon

Sometimes when comparing the performance of two algorithms such as in control, optimization, machine learning, etc. the comparison is done by running a number of simulations run on a set of benchmark problems for these algorithms, the statistical performance metrics are then derived from these simulation runs to compare their performances. However, it is usually not sufficient to claim one algorithm/method is better simply based on the average values of the performance metrics. In other words, performance comparison should also consider statistical hypothesis tests such as Student's t-test and Wilcoxon. Details of these methods can be found here:

https://en.wikipedia.org/wiki/Student's_t-test
http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test

This post is about how to do statistical hypothesis test in C++ using alglib

Step 1: Download AlgLib

Download the AlgLib from the following link:

http://www.4shared.com/zip/ZWXFztx-/alglib-250cpp.html

Step 2: Add AlgLib to C++ project

In this case, I am using VS2008 C++ IDE, unzip the downloaded AlgLib to the project solution folder, and add it to the C++ project by the following properties configuration:

1) Properties->Configuration Properties->C++->General->Additional Include Directories->$(ProjectDir)alglib-2.5.0.cpp\out
2) Properties->Configuration Properties->Linker->General->Additional Library Directories->$(ProjectDir)alglib-2.5.0.cpp\out
3) Properties->Configuration Properties->Linker->Input->libalglib.lib

Step 3: Student's t-test in C++
Suppose you implement your code in a source file main.cpp, define the Student's t-test as shown below in

#include "studentttests.h"
//data1: vector containing simulation results of a performance metric (say MetricA) for algorithm 1
//data2: vector containing simulation results of a performance metric (say MetricA) for algorithm 2
//if left-tail is less than the confidence threshold, left-tail rejected, and we have MetricA (algorithm 1) > MetricA (algorithm 2)
//if right-tail is less than the confidence threshold, right-tail rejected, and we have MetricA (algorithm 1) < MetricA (algorithm 2)
void ComputeStudentT(const std::vector<double>& data1, const std::vector<double>& data2, double& bothtails, double& lefttail, double& righttail)
{
 if(data1.empty() || data2.empty())
 {
  return;
 }

 ap::real_1d_array x;
 ap::real_1d_array y;
 
 int n=static_cast<int>(data1.size());
 x.setlength(n);
 for(int i = 0; i != n; i++)
 {
  x(i) = data1[i];
 }

 int m=static_cast<int>(data2.size());
 y.setlength(m);
 for(int i=0; i != m; ++i)
 {
  y(i)=data2[i];
 }

 /*************************************************************************
 Two-sample unpooled test

 This test checks three hypotheses about the mean of the given samples. The
 following tests are performed:
  * two-tailed test (null hypothesis - the means are equal)
  * left-tailed test (null hypothesis - the mean of the first sample  is
    greater than or equal to the mean of the second sample)
  * right-tailed test (null hypothesis - the mean of the first sample is
    less than or equal to the mean of the second sample).

 Test is based on the following assumptions:
  * given samples have normal distributions
  * samples are independent.
 Dispersion equality is not required

 Input parameters:
  X - sample 1. Array whose index goes from 0 to N-1.
  N - size of the sample.
  Y - sample 2. Array whose index goes from 0 to M-1.
  M - size of the sample.

 Output parameters:
  BothTails   -   p-value for two-tailed test.
      If BothTails is less than the given significance level
      the null hypothesis is rejected.
  LeftTail    -   p-value for left-tailed test.
      If LeftTail is less than the given significance level,
      the null hypothesis is rejected.
  RightTail   -   p-value for right-tailed test.
      If RightTail is less than the given significance level
      the null hypothesis is rejected.

   -- ALGLIB --
   Copyright 18.09.2006 by Bochkanov Sergey
 *************************************************************************/
 
 unequalvariancettest(x, n, y, m, bothtails, lefttail, righttail);
}

For ComputeStudentT() method, the parameter data1 is a vector containing simulation results of a performance metric (say MetricA) for algorithm 1, which is obtained from simulation runs on a benchmark problem (suppose there are 30 simulation runs, then data1 is a vector of length 30), while data2 is a vector containing results of MetricA for algorithm 2, which is obtained from simulation runs on the same benchmark problem.

Below shows how one can use the CompareStudentT() in the coding

RunSimulationsToObtainMetricAForAlgorithm1();
RunSimulationsToObtainMetricAForAlgorithm2();

std::vector<double> data1;
LoadMetricAForAlgorithm1IntoVector(data1);

std::vector<double> data2;
LoadmetricAForAlgorithm2IntoVector(data2);

double bothtails=0, lefttail=0, righttail=0;

double p_threshold=0.05; //set p threshold to 0.05 for 95% confidence level

ComputeStudentT(data1, data2, bothtails, lefttail, righttail);

/*
* two-tailed test (null hypothesis - the means are equal)
* left-tailed test (null hypothesis - the mean of the first sample  is
  greater than or equal to the mean of the second sample)
* right-tailed test (null hypothesis - the mean of the first sample is
  less than or equal to the mean of the second sample).
*/
if(bothtails < p_threshold)
{
 //null hypothesis rejected, the mean of data1 is either greater or less than tat of data2
 if(lefttail < p_threshold && righttail > p_threshold)
 {
  std::cout << "The true mean of MetricA(algorithm1) is smaller than tat of MetricA(algorithm2)" << std::endl;
 }
 else if(lefttail > p_threshold && righttail < p_threshold)
 {
  std::cout << "The true mean of MetricA(algorithm1) is greater than tat of MetricA(algorithm2)" << std::endl;
 }
 else
 {
  std::cerr << "error: t stat failed" << std::endl;
  exit(0);
 }
}


Step 4: Wilcoxon test in C++ 

Below shows the Wilcoxon test method in C++, the interface and usage of ComputeWilcoxon() method is same as ComputeStudentT() method

#include "wsr.h"

//if left-tail is less than the confidence threshold, left-tail rejected, and we have data1 > data2
//if right-tail is less than the confidence threshold, right-tail rejected, and we have data2 < data1
void ComputeWilcoxon(const std::vector<double>& data1, const std::vector<double<& data2, double& bothtails, double& lefttail, double& righttail)
{
 if(data1.empty() || data2.empty())
 {
  return;
 }

 ap::real_1d_array x;
 ap::real_1d_array y;
 
 int n=static_cast<int>(data1.size());
 int m=static_cast<int>(data2.size());

 if(n > m)
 {
  n=m;
 }

 x.setlength(n);
 for(int i = 0; i != n; i++)
 {
  x(i) = (data1[i] - data2[i]);
 }

 double assumed_median=0; //the given value

 /*************************************************************************
 Wilcoxon signed-rank test

 This test checks three hypotheses about the median  of  the  given sample.
 The following tests are performed:
  * two-tailed test (null hypothesis - the median is equal to the  given
    value)
  * left-tailed test (null hypothesis - the median is  greater  than  or
    equal to the given value)
  * right-tailed test (null hypothesis  -  the  median  is  less than or
    equal to the given value)

 Requirements:
  * the scale of measurement should be ordinal, interval or  ratio (i.e.
    the test could not be applied to nominal variables).
  * the distribution should be continuous and symmetric relative to  its
    median.
  * number of distinct values in the X array should be greater than 4

 The test is non-parametric and doesn't require distribution X to be normal

 Input parameters:
  X       -   sample. Array whose index goes from 0 to N-1.
  N       -   size of the sample.
  Median  -   assumed median value.

 Output parameters:
  BothTails   -   p-value for two-tailed test.
      If BothTails is less than the given significance level
      the null hypothesis is rejected.
  LeftTail    -   p-value for left-tailed test.
      If LeftTail is less than the given significance level,
      the null hypothesis is rejected.
  RightTail   -   p-value for right-tailed test.
      If RightTail is less than the given significance level
      the null hypothesis is rejected.

 To calculate p-values, special approximation is used. This method lets  us
 calculate p-values with two decimal places in interval [0.0001, 1].

 "Two decimal places" does not sound very impressive, but in  practice  the
 relative error of less than 1% is enough to make a decision.

 There is no approximation outside the [0.0001, 1] interval. Therefore,  if
 the significance level outlies this interval, the test returns 0.0001.

   -- ALGLIB --
   Copyright 08.09.2006 by Bochkanov Sergey
 *************************************************************************/
 wilcoxonsignedranktest(x, n, assumed_median, bothtails, lefttail, righttail);
}


Access SQLite using C++

This is a description of accessing SQLite using C++

Step 1: Download the CppSQLite

For me, I have been using the version which can be downloaded from:

http://www.4shared.com/zip/aNL2EdT_/sqlite.html

Step 2: Build the CppSQLite library

In this example, I am using VS2008 C++ IDE,

1) Extract the downloaded content to the folder sqlite
2) Open sqlite\SQLite_Static_Library\SQLite_Static_Library.sln
3) You may need to change the runtime libraries of the project to match those of the executable that will include the libraries, in order to avoid linker errors.
4) Build the library.

Step 3: Add the CppSQLite to your project

1) copy the sqlite folder to your solution folder
2) Include the library directory in your application (Project->Properties->Configuration Properties->Linker->General->Additional Library Directories->["$(ProjectDir)sqlite\SQLite_Static_Library\release"])
3) Include the static library built in step 2 (Project->Properties->Configuration Properties->Linker->Input->Additional Dependencies->[SQLite_Static_Library.lib])
4) Add the C++ wrapper to your project.  It's in the sqlite root dir:

      CppSQLite3.h
      CppSQLite3.cpp

Step 4: Implement code to access SQLite

The following a simple singleton class written in C++:

#ifndef _H_DB_MANAGER_H
#define _H_DB_MANAGER_H

#include <sstream>
#include <ctime>
#include "CppSQLite3.h"

class DBManager
{
public:
 virtual ~DBManager()
 {
  
 }

private:
 DBManager()
 {
  
 }

 DBManager(const DBManager& rhs) { }
 DBManager& operator= (const DBManager& rhs) { return *this; }

public:
 void record_data(int attr1_value, const std::string& attr2_value, int attr3_value)
 {
  std::ostringstream oss;
  oss << "INSERT INTO demo_table (attr1, attr2, attr3) VALUES (" << attr1_value << ", '" << attr2_value << "', " << attr3_value << ");" ;
  try{
   mDB.execDML(oss.str().c_str());
  }catch(CppSQLite3Exception& e)
  {
   std::cerr << e.errorCode() << ": " << e.errorMessage() << "\n";
  }
 }

public:
 static DBManager* getSingletonPtr()
 {
  static DBManager theInstance;
  return &theInstance;
 }

public:
 void open(const char* dbname)
 {
  try{
   remove(dbname);
   mDB.open(dbname);

   mDB.execDML("CREATE TABLE demo_table (id INTEGER PRIMARY_KEY, attr1 INTEGER, attr2 TEXT, attr3 INTEGER);");
  
  }catch (CppSQLite3Exception& e)
  {
   std::cerr << e.errorCode() << ":" << e.errorMessage() << "\n";
  }
 }
 void close()
 {
  mDB.close();
 }

private:
 CppSQLite3DB mDB;
};
#endif

Below is a simple explanation of the database manager class
  • The open() method recreate the database, and then create a datatable "demo_table" in the database file with three fields: attr1, attr2, attr3, attr1 and attr3 are INTEGER while attr2 is a TEXT. 
  • The record_data() method record a single row into the database "demo_table" 
  • The close() method should be called at the end of database operation to create database connection


To use the singleton class above, it is very easy, below is a simple example:
#include "DBManager.h"
DBManager::getSingletonPtr()->open("demo.db");
DBManager::getSingletonPtr()->record_data(1, "Hello World", 2);
DBManager::getSingletonPtr()->close();

Tuesday, July 16, 2013

Some good resources for learning OpenFOAM

Basic Tutorial:

http://web.student.chalmers.se/groups/ofw5/Basic_Training/gettingStarted.pdf
http://web.student.chalmers.se/groups/ofw5/Program.htm

Course Material:
http://www.tfd.chalmers.se/~hani/kurser/OS_CFD_2010/

Material Archive:
http://powerlab.fsb.hr/ped/kturbo/OpenFOAM/docs/

At this point, I cannot find a good book on OpenFOAM, some suggested a good starting point is to learn CFD using book such as "Ferziger, Peric, Computational Methods for Fluid Dynamics, Springer".


Thursday, July 11, 2013

Compile and run Taucs on Windows

Taucs (http://www.tau.ac.il/~stoledo/taucs/) is a library of sparse linear solvers, which was frequently used in computational geometry and mesh processing. I have built the Taucs on Windows and made a small demo program for using Taucs in VS2010, which will run on Windows platform and solve a set of linear equations. The package can be downloaded from:

http://www.4shared.com/zip/b35JMBfc/Taucs.html

The process of building and test-running Taucs on Windows is as follows: after download the package from the link above, cd to the taucs_full folder, and enter the following command:

$"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat"
$configure.bat
$nmake
$bin\win32\direct -mesh2d 400 -log stdout -snmf
$cl -c -Isrc -Ibuild\win32 -EHsc test_taucs.cpp
$cl test_taucs.obj libtaucs.lib libmetis.lib liblapack.lib libf77blas.lib libcblas.lib libatlas.lib vcf2c.lib -link -LIBPATH:lib\win32 -LIBPATH:external\lib\win32
$test_taucs.exe

To start a C++ project that uses Taucs, copy the Taucs_full to the solution folder, then add the following settings to the C++ project properties page.

IncludePath:
$(SolutionDir)taucs_full\build\win32
$(SolutionDir)taucs_full\src

LibPath:
$(SolutionDir)taucs_full\external\lib\win32
$(SolutionDir)taucs_full\lib\win32

Additional Lib:
libtaucs.lib
libmetis.lib
liblapack.lib
libf77blas.lib
libcblas.lib
libatlas.lib
vcf2c.lib
blas_win32.lib

The above details of these configurations and settings can be found in the RunTaucs project in the package from the above link.


Tuesday, July 9, 2013

Add TinyXml support to Qt Application

Download and unzip the tinyxml in the project folder of the Qt application. cd to the Qt project folder and enter the following command in the command prompt:
$qmake -project

This will generate the xxx.pro (where xxx refers to the name of the Qt project folder), in the xxx.pro insert the following lines below the line starting with "TARGET = ":

DEPENDPATH += . tinyxml
INCLUDEPATH += . tinyxml

Step-by-step to install Shark Lib on Ubuntu

Step 1: Install g++
Check whether g++ compiler has been installed on the target Linux machine by entering the following in the command prompt:
$g++

If the target Linux machine indicates no g++ compiler is installed on the machine, proceed to install the compiler by entering the following in the command prompt:
$sudo apt-get install g++

Step 2: Install CMake
Check whether cmake has been installed on the target linux machine, by entering the following in the command prompt:
$cmake -help

If the target linux machine indicates no cmake is installed on the machine, proceed to install cmake by entering the following in the command prompt:
$sudo apt-get install cmake

Step 3: Install Shark
To install Shark library, download the software package shark-2.3.4.zip from
http://sourceforge.net/projects/shark-project/files/

Unzip it (to unzip, if you are using ubuntu, right-click the zip file and click "Extract Here" from the context menu), next cd to the unzipped "Shark" folder, and run the following commands:
$cmake
$make
$sudo make install
This will install Shark (where using ubuntu, the installed directory can be found at usr/local)

Step 4: Makefile
Below is an example of the makefile which include the Shark lib for building the solver (the highlighted part is the Shark lib related)

SHARKHOME=/usr/local

LDLIBS=-lshark
LDFLAGS=-L${SHARKHOME}/lib -Wl,-rpath,${SHARKHOME}/lib
CXXFLAGS=-O3 -I${SHARKHOME}/include

PROBLEMDIR=..
OBJDIR=Objs
MDOLIB=../../../Solvers
SOLVER=../../../Solvers/NSGA2

CC=g++
SOURCES       = $(SOLVER)/Nsga2.cpp \
main.cpp \
$(PROBLEMDIR)/Problem_TNK.cpp \
$(MDOLIB)/Problem.cpp 
OBJECTS       = $(OBJDIR)/Nsga2.o \
$(OBJDIR)/main.o \
$(OBJDIR)/Problem_TNK.o \
$(OBJDIR)/Problem.o 

EXECUTABLE=NSGA2

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) 
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS) $(LDLIBS) 

####### Compile

$(OBJDIR)/Nsga2.o: $(SOLVER)/Nsga2.cpp $(SOLVER)/Nsga2.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $(OBJDIR)/Nsga2.o $(SOLVER)/Nsga2.cpp

$(OBJDIR)/Problem.o: $(MDOLIB)/Problem.cpp $(MDOLIB)/Problem.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $(OBJDIR)/Problem.o $(MDOLIB)/Problem.cpp

$(OBJDIR)/Problem_TNK.o: $(PROBLEMDIR)/Problem_TNK.cpp $(PROBLEMDIR)/Problem_TNK.h \
$(MDOLIB)/Problem.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $(OBJDIR)/Problem_TNK.o $(PROBLEMDIR)/Problem_TNK.cpp

$(OBJDIR)/main.o: main.cpp $(SOLVER)/Nsga2.h  
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $(OBJDIR)/main.o main.cpp


####### Clean

clean: 
rm -f *.o *~ *.out *.txt
rm -f ${EXECUTABLE} ${OBJECTS}




Step-by-step for installing QwtPlot on Ubuntu Linux

Step 1: Install g++
Check whether g++ compiler has been installed on the target Linux machine by entering the following in the command prompt:
$g++

If the target Linux machine indicates no g++ compiler is installed on the machine, proceed to install the compiler by entering the following in the command prompt:
$sudo apt-get install g++

Step 2: Install CMake
Check whether cmake has been installed on the target linux machine, by entering the following in the command prompt:
$cmake -help

If the target linux machine indicates no cmake is installed on the machine, proceed to install cmake by entering the following in the command prompt:
$sudo apt-get install cmake


Step 3: Install Qt
Check whether Qt has been installed on the target linux machine, by entering the following in the command prompt:
$qmake -help

If the target linux machine indicates no Qt is installed on the machine, proceed to install Qt by entering the following in the command prompt:
$sudo apt-get install libqt4-dev qt4-dev-tools

Step 4: Install QwtPlot
To install QwtPlot, download the software package qwt-6.0.1.zip from 

Unzip the package (to unzip, if you are using Ubuntu, right-click the zip file and click "Extract Here" from the context menu). Next from the terminal, cd to the unzipped folder "qwt-6.0.1", and run the following command:
$qmake
This will generate the Makefile require to build QwtPlot, next run the command:
$make
This will build the QwtPlot, next run the command:
$sudo make install
This will install QwtPlot (when using ubuntu, the installed directory can be found at usr/local/qwt-6.0.1). The final step is to add the QwtPlot export statement into the .bashrc file in the /home/[username] directory ([username] refers to the linux login id). To add the export statement, run the following commands in the terminal:
$cd /home/[username]
$ls -a
$gedit .bashrc
In the .bashrc file that opened, add the following two lines to the bottom of the file
export QWT=/usr/local/qwt-6.0.1
export LD_LIBRARY_PATH=$QWT/lib:$LD_LIBRARY_PATH

Step 5: Build Qt application using QwtPlot
To build the Qt application with QwtPlot data visualization, enter the following command with the  Qt project folder:
$qmake -project

This will build the xxx.pro (where xxx refers to the project name), in the xxx.pro, just below the line starting wtih "INCLUDEPATH" (or below the line starting with "TARGET=" if line starting with "INCLUDEPATH"  is not in xxx.pro), insert the following lines:
QWT_VER_MAJ      = 6
QWT_VER_MIN      = 0
QWT_VER_PAT      = 1
QWT_VERSION      = $${QWT_VER_MAJ}.$${QWT_VER_MIN}.$${QWT_VER_PAT}

QWT_DIR = /usr/local/qwt-$$QWT_VERSION 

LIBS += -L$$QWT_DIR/lib -lqwt
INCLUDEPATH += $$QWT_DIR/include

Now run the following command to build the project
$qmake
$make


Setup g++ and CMake on Ubuntu

Step 1: Install g++
Check whether g++ compiler has been installed on the target Linux machine by entering the following in the command prompt:
$g++

If the target Linux machine indicates no g++ compiler is installed on the machine, proceed to install the compiler by entering the following in the command prompt:
$sudo apt-get install g++

Step 2: Install CMake
Check whether cmake has been installed on the target linux machine, by entering the following in the command prompt:
$cmake -help

If the target linux machine indicates no cmake is installed on the machine, proceed to install cmake by entering the following in the command prompt:
$sudo apt-get install cmake

Step-by-step for installing Qt on Ubuntu Linux

Check whether Qt has been installed on the target linux machine, by entering the following in the command prompt:
$qmake -help

If the target linux machine indicates no Qt is installed on the machine, proceed to install Qt by entering the following in the command prompt:
$sudo apt-get install libqt4-dev qt4-dev-tools

Download and Install OpenGL GLUT, GLUI on Linux

Download and Install OpenGL GLUT, GLUI on Linux

OpenGL GLUT and GLUI are used to build a simple visualization application for demonstrating my FreeStyle application and library. To download and install glut and glui for openGL, run the following commands:
$sudo apt-get install update
$sudo apt-get install libglui-dev
The following command is optional, as glut may already come with the particular version of Linux

$sudo apt-get install libglew-dev freeglut3-dev

Step-by-step for building OpenMesh library on Linux

1       Download and Install CMAKE

This step may be optional, to download and install cmake if not available or outdated, run the following command:
$sudo apt-get install cmake

2       Download and Compile OpenMesh Library

Openmesh library is used to store and visualize the 3D STL model, it can be downloaded from:

to compile it running the following command
$cd OpenMesh-2.3.1
$rm -rf build
$mkdir build
$cd build
$cmake .. -DCMAKE_BUILD_TYPE=Release
$make
$sudo make install

$sudo ldconfig -v

Sunday, January 9, 2011

Delete a folder in Qt

This code snippet allows programmer to delete a folder in Qt

#include <QDir>

void deleteDir(const std::string& foldername)
{

  QDir dir;
  dir.rmdir(foldername.c_str());
}

List directories in Qt

This code snippet allows programmer to list directories in a parent directory "C:\temp" by using Qt API

#include <QDir>

void list(QStringList& dirnames)
{

         QDir currentDir("C:\\temp");

currentDir.setFilter(QDir::Dirs);
QStringList entries = currentDir.entryList();
for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry )
{
//std::cout << *entry << std::endl;
QString dirname=*entry;
if(dirname != tr(".") && dirname != tr(".."))
{
dirnames.add(dirname);
}
}
}

Monday, January 3, 2011

The procedure entry point _Z5qFreePv could not be located in the dynamic link library qtCore4.dll

To remove the issues with release build issue error "The procedure entry point _Z5qFreePv could not be located in the dynamic link library qtCore4.dll":
  1. Track down the source of the dll using depends.exe (downloadable from http://www.dependencywalker.com/)
    • Source of Problem 1: debug version of an app exe compiled and opened fine, release version of same app would compile fine but exe failed due to "entry point" in dll failure. There are some old QtCore and QtGui dll's in System32 directory.
    • Solution 1: The release version was referencing these dll's. I removed them.
    • Source of Problem 2: the QtCore.dll referenced is pointed to "C:\Qt\2009.02\bin" instead of "C:\Qt\2009.02\qt\bin"
    • Solution 2: remove "C:\Qt\2009.02\bin" from the path environmental variables