Monday, 23 December 2013

Arachnophobia !

This is just a little too freaky.

Dancing Robugtix T8 robot spider controlled by an XMOS xCORE device. :
http://www.youtube.com/watch?v=Yo2TUIEXJig

Enthusiastically reviewed by Adam Savage from Mythbusters :
http://www.youtube.com/watch?v=-vVblGlIMgw


If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

Sunday, 15 December 2013

How To Use MathGL Under Windows with the Microsoft Visual Studio 2010 64 bit compiler

Introduction

This solution is heavily based on the solution provided in the following tutorial : https://groups.google.com/forum/#!topic/mathgl/t-X9eg-5joU.
My thanks to RK for helping me find a solution.
I have found some changes in the packages since RK's post and I also needed 64 bit GLUT libraries so I have made minor some changes to his procedures.

Note : While this solution worked, I found that the MathGL functionality didn't quite stack up to that available in GNUPlot, see here for further details : http://realgonegeek.blogspot.co.uk/2014/01/interfacing-cc-to-gnuplot.html.

Requirements

  Microsoft Visual Studio 2010 : go.microsoft.com/fwlink/?LinkId=244366
  Microsoft SDK v7.1 64 bit compiler. Installation instructions are here : http://realgonegeek.blogspot.co.uk/2013/08/microsoft-visual-c-2010-sdk-v71-64-bit.html
  MathGL 2.2 source code : http://sourceforge.net/projects/mathgl/files/mathgl/mathgl%202.2/mathgl-2.2.tar.gz/download
  FreeGlut 2.8.1 (Martin Payne's Windows MSVC binaries : http://www.transmissionzero.co.uk/software/freeglut-devel/
  CMake 2.8.11 : http://www.cmake.org/files/v2.8/cmake-2.8.12.1-win32-x86.exe

Procedures
1. Follow steps 1 to 3 in RK's tutorial except using freeglut instead of the original GLUT.
2. Before running CMake-gui ensure that you have configured the Microsoft Compiler environment using :
  "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" amd64
3. Follow steps 4 to 6 in RK's tutorial and choose "Visual Studio 10 Win64" in step 6.
4. Tick the Advanced box in CMake-gui to view all of the requried entries (e.g  GLUT_INCLUDE_DIR and GLUT_glut_LIBRARY)
5. Follow the rest of RK's tutorial
6. In your chosen source code folder create the following file (e.g. example.cpp) :

#pragma warning( disable: 4190 )    // Disable complex number warning

#include <mgl2/glut.h>

int sample(mglGraph *gr)
{
  mglData dat (100);
  for (long i = 0; i < 40; i++)
  {
    gr->NewFrame ();          // start frame
    gr->Box ();               // some plotting
    gr->Axis ();              // draw axis
    for (long j = 0; j < dat.nx; j++)
      dat.a[j] = sin (M_PI*j/dat.nx+M_PI*0.05*i);
    gr->Plot (dat, "b");      // "b" is colour ??
    gr->EndFrame ();          // end frame
    gr->WriteFrame ();        // save frame
  }
  return 0;
}

int main (int argc, char **argv)
{
  mglGLUT gr (sample, "MathGL examples");
  return 0;
}

7. Open a command window into your source folder and ensure the Microsoft Compiler environment is correctly configured, as per step 2. above.
8. Configure the compiler environment variables to locate the header and library files e.g. :
  set INCLUDE=%INCLUDE%;c:\mathgl-2.2\include
  set LIB=%LIB%;c:\mathgl_v2.2\src\Release;C:\mathgl_v2.2\widgets\Release
9. Compile example.cpp using the following command line :
  cl /EHsc example.cpp mgl-glut.lib
10. Copy the required dlls to the current folder :
  copy /Y C:\Users\johne2\Desktop\Graphics\mathgl\mathgl_v2.2\mathgl-2.2-cmake\src\Release\*.dll
  copy /Y C:\Users\johne2\Desktop\Graphics\mathgl\mathgl_v2.2\mathgl-2.2-cmake\widgets\Release\*.dll
  copy /Y C:\Users\johne2\Desktop\Graphics\mathgl\Glut\freeglut\bin\x64\*.dll
11. Execute example.exe and you should see a scrolling sine wave.
12. Play with MathGL :-)

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

Friday, 13 September 2013

How To Access A Windows Library From Python, Using SWIG

In the previous blog (How To Build Windows Static And Dynamic Link Libraries) I described how to generate static and dynamic link libraries from C functions. This blog describes how to call these functions fom Python. In this example we will access the same VectorScalarMultiply function. We will use SWIG (http://www.swig.org) to provide the wrapper between Python and C. SWIG is a really useful tool for importing C libraries into almost all common scritping languages like Python, PERL, Java etc.

First off, we need to provide a SWIG interface file (Multiply.i) to tell SWIG about our library. SWIG is very powerful because it is able to obtain a lot of information from the library header file, for example, it can work out that Data_t is typedef'd to a double. However we do need to assist SWIG and tell it that we are going to be handling arrays of floating point data.
To do this we include the SWIG interface file "carrays.i" and tell SWIG we want to use the array_class interface. The complete interface file is shown here :

%module Multiply_wrap

%include "typemaps.i"
%include "carrays.i"

%array_class(double, doubleArray); /* Include support for "double *" functions */
%array_class(long, longArray); /* Include support for "long *" functions */

%{
#include "Multiply.h"
%}

%include "Multiply.h"

With this file we can now create the importable Python module that contains the functions we want to access. This is essentially a two stage process :
    Configure SWIG
    Compile the library into a Python importable module

Here is a complete batch file for creating a Python wrapper for accessing the library. Note that we are calling the new DLL (Multiply_wrap.dll) to differentiate it from Multiply.dll created in the earlier blog. Note that Python expects the file to be called Multiply_wrap.pyd so we will also rename it.
Please refer to the remarks for additional comments.

rem Delete the wrapper c file so that if it is not regenerated using swig then the compile will fail
rem this is helpful for development because if the you don't delete the old file then the compiler
rem will just process that, which might not be what you want !
del Multiply_wrap_wrap.c

c:\swig\swig -python -includeall Multiply_wrap.i

cl -Od -MD -DNDEBUG -DWIN32 -IC:\Anaconda\envs\py33\include -D_CONSOLE -DSTATIC_LIB=1 -DNO_STRICT Multiply_wrap_wrap.c /link user32.lib Multiply.lib C:\Anaconda\envs\py33\libs\python33.lib /DLL /out:Multiply_wrap.dll /NODEFAULTLIB:LIBCMT

rem The Python module should have extension .pyd
rem so we will delete the old one and rename the newly created dll
if exist _Multiply_wrap.pyd del /Q _Multiply_wrap.pyd

ren Multiply_wrap.dll _Multiply_wrap.pyd

Finally, we need to write a test script to access the C coded function.
This function includes some additional functionality that is not strictly necessary but this is to show some additional useful techniques such as :
    Printing the attributes of the library
    Converting Python lists to C arrays and back again
    Accessing the values of C #define constants from Python
Here is the complete Test.py script :

import multiply_wrap                        # Note the module name must be lower case !

print ('')
print ('Library attributes :')              # Print the attributes of the library
for a in dir(Multiply_wrap):
    print (a)
print ('')

a = [1.2, 3.4, 5.6, 7.8, 9.0]
b = [1000.1, 100.2, 1000.3, 1000.4, 1000.5] # Destination array to put results into

print ('')
print ('PI = ')                             # Print a constant defined in C
print (Multiply_wrap.PI)
print ('')

p_a = Multiply_wrap.doubleArray (5)
p_b = Multiply_wrap.doubleArray (5)

for index, item in enumerate(a):            # Copy data to array p_a
    p_a[index] = item

print ('a = ')                              # Print contents of a
for i in range(0,5):
    print(p_a[i])
print ('')

Multiply_wrap.VectorScalarMultiply (p_a, Multiply_wrap.TWO_PI, p_b, 5)

for i in range(0,5):                        # Copy data to b
    b[i] = p_b[i]

print ('Scaled a = ')
print (b)
print ('')

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

Thursday, 12 September 2013

How To Build Windows Static And Dynamic Link Libraries With The Microsoft Compiler

Creating a C/C++ statically linked library is easy : compile the library code to object code (without creating an executable) then call the lib utility. In this case the same header file that declares the function can be used for both the library and the application.
Creating a dynamic linked library is a little bit more involved because the header file needs to be able to declare the functions for both "export" (from the DLL) and "import" (into the application). In this case the functions must be declared differently depending on whether they are being used in the library or the application.
Using some simple conditional compilation techniques allows the library functions to be written in a way that will support both static and dynamic linking.

In this example I am going to implement a common DSP function, vector scalar multiplication and call the function VectorScalarMultiply().

Using floating point data this function has the following declaration :

void VectorScalarMultiply (const double *,  /* Pointer to source array */
    const double,                           /* Multiplier */
    double *,                               /* Pointer to destination array */
    const long);                            /* Array length */

There are several things we can do to improve this function and the first is to make it portable to use different data types. We will use a typedef for this and the following code shows how to declare the typedef for double precision floating point numbers :

typedef double  Data_t;                 /* Data type */

Now, if we want to change the data type of the function all we need to do is change the typedef.

Secondly we can write this function declaration so that it is compilable into both static and dynamic libraries, as described above. For this we will use the following conditional compilation code :

#if defined (_MSC_VER)                  /* Defined by Microsoft compilers */
#include <windows.h>                    /* Required for Windows applications */

#if defined (STATIC_LIB)                /* Create statically linked library */
#define FUNC_DECL                       /* Not used with statically linked library */
#else                                   /* Create dynamically linked  library */
#if defined (DLL_SOURCE)                /* Defined on command line, if rebuilding DLL */
#define FUNC_DECL       __declspec(dllexport) WINAPI    /* DLL export function - used in DLL source */
#else
#define FUNC_DECL       __declspec(dllimport) WINAPI    /* DLL import function - used in Application */
#endif      // DLL_SOURCE
#endif      // STATIC_LIB
#endif      // _MSC_VER

In the above code, we will use a declaration on the compiler command line for the following values (-D is the Microsoft command line switch):
-DSTATIC_LIB=1
This is used to tell the compiler that the function is being compiled into a static library and the result is that the value FUNC_DECL becomes undeclared.
-DDLL_SOURCE=1
This is used to tell the compiler that the function is being compiled into a dynamic library and the result is that the value FUNC_DECL becomes "__declspec(dllexport) WINAPI".
The other option (if neither of these is declared) is : "__declspec(dllimport) WINAPI", which is used to include the header into the application.

This results in the following declaration :

void FUNC_DECL VectorScalarMultiply (const Data_t *,    /* Pointer to source array */
    const Data_t,                           /* Multiplier */
    Data_t *,                               /* Pointer to destination array */
    const long);                            /* Array length */

So the complete header file (which we will call Multiply.h) is as follows and we have defined a constant PI so that we can use it in the test application later on :

#define PI      3.141592

typedef double  Data_t;                 /* Data type */

#if defined (_MSC_VER)                  /* Defined by Microsoft compilers */
#include <windows.h>                    /* Required for Windows applications */

#if defined (STATIC_LIB)                /* Create statically linked library */
#define FUNC_DECL                       /* Not used with statically linked library */
#else                                   /* Create dynamically linked  library */
#if defined (DLL_SOURCE)                /* Defined on command line, if rebuilding DLL */
#define FUNC_DECL       __declspec(dllexport) WINAPI    /* DLL export function - used in DLL source */
#else
#define FUNC_DECL       __declspec(dllimport) WINAPI    /* DLL import function - used in Application */
#endif      // DLL_SOURCE
#endif      // STATIC_LIB
#endif      // _MSC_VER

#if defined (SWIG)                      /* Is this header included by SWIG ? */
#define FUNC_DECL
#endif

void FUNC_DECL VectorScalarMultiply (const Data_t *,    /* Pointer to source array */
    const Data_t,                           /* Multiplier */
    Data_t *,                               /* Pointer to destination array */
    const long);                            /* Array length */

Now we need to write the function, as follows, which we will put in a source file called Multiply.c :

#include "Multiply.h"

void FUNC_DECL VectorScalarMultiply (const Data_t * pSrc,
    const Data_t Multiplier,
    Data_t * pDst,
    const long SampleLength)

{
    register long   i;

    for (i = 0; i < SampleLength; i++)
    {
        *pDst++ = *pSrc++ * Multiplier;
    }

}       /* End of VectorScalarMultiply() */

This includes FUNC_DECL, for using the function in a static or dynamic link library. This also includes the data type declared as Data_t.

Finally we need to write a test application (Test.c), as follows :

#include "Multiply.h"
#include <stdio.h>

#define ARRAY_LENGTH    5L

void main (void)

{
    Data_t  a[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    Data_t  b[ARRAY_LENGTH];
    long     i;

    VectorScalarMultiply (a, PI, b, ARRAY_LENGTH);

    for (i = 0; i < ARRAY_LENGTH; i++)
    {
        printf ("b[%ld] = %lf\n", i, b[i]);
    }
}

Now all we need to do is compile and test our library and application. The appropriate command lines are as follows :

Static Linked Library :
To build the library :
cl /c -DSTATIC_LIB=1 Multiply.c
To add the module into the library (called Multiply.lib) :
lib Multiply.obj
To build the application :
cl -DSTATIC_LIB=1 Test.c Multiply.lib

Dynamic Linked Library :
To build the library :
cl /LD -DDLL_SOURCE=1 Multiply.c
This creates a dll called Multiply.dll and a library called Multiply.lib. The lib is a wrapper for the dll. It is entirely possible to access Multiply.dll directly from a C application but this is the easiest method.
To build the test application :
cl Test.c Multiply.lib

Now just execute Test.exe and the application should call the library function.

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

Saturday, 31 August 2013

How To Plot Data From C Using Matplotlib

Following on from my earlier blog entitled "How To Pass A C Array To Python Solution" (http://realgonegeek.blogspot.co.uk/2013/08/how-to-pass-c-array-to-python-solution.html) here is some simple code to plot the same data using Matplotlib.

Note : While this solution worked, I found that it was very slow because of the time required to load Python so I ended up reverting back to GNUPlot, see here for further details : http://realgonegeek.blogspot.co.uk/2014/01/interfacing-cc-to-gnuplot.html.

All you need to do is take the earlier C example, change the Python method from PrintArray to PlotArray and recompile.

def PlotArray (a):
    import matplotlib.pyplot as pp
    from matplotlib.font_manager import FontProperties
    import numpy as np
    
    p1, = pp.plot (a, label = "line 1", color='red')

    ax = pp.subplot (111)
    box = ax.get_position ()
    ax.set_position ([box.x0, box.y0, box.width * 0.85, box.height]) # Shink x axis to fit legend
    fontP = FontProperties ()
    fontP.set_size ('small')

    pp.legend (loc=2, prop = fontP, fancybox = True, bbox_to_anchor=(1, 1.0))
    pp.title ("Title")
    pp.xlabel ("X-Axis")
    pp.ylabel ("Y-Axis")
    pp.ylim (ymin = 0, ymax = 10)
    pp.grid (True)

    pp.show (block=True)

    c = 0
    return c

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

How To Pass A C Array To Python Solution

While I commonly use C or C++ for processing signals there are not too many options available for displaying the results graphically so I have been looking at using Matplotlib for the display. The first problem I encountered is how to pass an array of floating point data from C to Python.
There are several options and a lot of forum discussions on the subject but I couldn't find a simple solution. So here is one that I developed earlier.
This example works with an Anaconda/Python v3.3 installation with the 64 bit Microsoft compiler.

See here for an introduction to  Anaconda/Python v3.3 installation and calling Python from the 64 bit Microsoft compiler : http://realgonegeek.blogspot.co.uk/2013/08/how-to-embed-python-pylab-into-64bit.html.

Here is the C code :

#include <Python.h>
#include <stdio.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "C:\Anaconda\envs\py33\Lib\site-packages\numpy\core\include\numpy\arrayobject.h"

double Array [] = {1.2, 3.4, 5.6, 7.8};

int main (int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
    npy_intp dims[1] = { 4 };
    PyObject *py_array;

    Py_Initialize ();
    pName = PyUnicode_FromString ("PrintArray");
    // PyUnicode_FromString error checking here

    pModule = PyImport_Import (pName);                  // Load the module object
    // PyImport_Import error checking here
    Py_DECREF(pName);

    pFunc = PyObject_GetAttrString (pModule, "PrintArray");        // pFunc is a new reference
    // PyObject_GetAttrString error checking here

    import_array ();                                    // Required for the C-API : http://docs.scipy.org/doc/numpy/reference/c-api.array.html#importing-the-api

    py_array = PyArray_SimpleNewFromData (1, dims, NPY_DOUBLE, Array);
    // PyArray_SimpleNewFromData error checking here

    pDict = PyModule_GetDict (pModule);                 // pDict is a borrowed reference

    pArgs = PyTuple_New (1);
    PyTuple_SetItem (pArgs, 0, py_array);

    pFunc = PyDict_GetItemString (pDict, "PrintArray"); // pFunc is also a borrowed reference

    if (PyCallable_Check (pFunc)) 
    {
        PyObject_CallObject (pFunc, pArgs);
    } else 
    {
        printf ("Function not callable !\n");
    }

    Py_DECREF (py_array);                               // Clean up
    Py_DECREF (pModule);
    Py_DECREF (pDict);
    Py_DECREF (pFunc);

    Py_Finalize ();                                     // Finish the Python Interpreter

    return 0;
}

Here is the python script to print the contents of the array :

def PrintArray (a):
    print ("Contents of a :")
    print (a)
    c = 0
    return c

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

How To Embed Python PyLab Into A 64bit Windows C Application

Here is a quick solution for embedding PyLab into a 64bit Windows C app. It was a bit fiddly to get setup so after a few trips down blind alleys, here is what I did.

The easiest way to get a Python installation that includes PyLab, Matplotlib, Numpy, Scipy etc is to download Anaconda from : http://www.continuum.io/downloads. In my case I wanted to use the Python v3.3 version under 64 bit Windows. The default Anaconda installation is for v2.x but it is very easy to update to Python v3.3 using conda. form C:\Anaconda type the following command :
conda create -n py33 python=3.3 anaconda

In order to use the v3.3 installation, prepend the following to the PATH environment variable :
C:\Anaconda\envs\py33;C:\Anaconda\envs\py33\Scripts;

Although Anaconda works very well from Python scripts I found that I need to set the following PYTHONPATH environment variable :
set PYTHONPATH=C:\Anaconda\envs\py33;C:\Anaconda\envs\py33\Lib;C:\Anaconda\envs\py33\DLLs

To configure the Visual C compiler for 64 bit mode :
call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" amd64
For further details on installing the 64 bit Microsoft compiler, please see here :
http://realgonegeek.blogspot.co.uk/2013/08/microsoft-visual-c-2010-sdk-v71-64-bit.html

To compile the app use the following command line :
cl example.c -IC:\Anaconda\envs\py33\include C:\Anaconda\envs\py33\libs\python33.lib /link /MACHINE:X64

If you want to try it, here is a quick test program :

#include "Python.h"
int main()
{
Py_Initialize ();
PyRun_SimpleString ("import sys");
PyRun_SimpleString ("import pylab");
PyRun_SimpleString ("print(sys.version)");
PyRun_SimpleString ("print()");
PyRun_SimpleString ("pylab.plot(range(10))");
PyRun_SimpleString ("pylab.show()");
Py_Exit(0);
return 0;
}

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix