Friday, August 2, 2013

can Pyjamas rise from its ashes?

As a quick follow-up to my article about pyjamas being hijacked, there's an interesting blog article (in French) pointing out the existence of a new incarnation of the original Pyjamas project set up by Luke Leighton at http://pyj.be. According to that blog article this new initiative was sparked by Goffi, the author of the blog article.

Given that the hijacked project, while it has seen some contributions from different people, seems to have slowed down considerably since the debacle (although it's possible that people are developing awesome stuff in their forks), I'm curious to see what this intiative - if anything - will do to make pyjamas more popular again.

Here are two screenshots comparing the recent git histories.

recent git history of the hijacked project at pyjs.org

recent git history of the reinstated pyjamas at pyj.be


Saturday, July 13, 2013

Solving the towers of Hanoi using Lindenmayer systems

Introduction

What I'm about to describe is a funny side result of a technique to transform recursion to iteration, derived mathematically in my PhD thesis "Platform-independent source code transformations for task concurrency management", written 10 years ago. Time flies!

Funny how after so many years I consider exactly this little side-result to be the most intriguing result of my thesis. The mathematical proof of how it works is best left to the thesis itself, but I will try to demonstrate you how you could calculate the j-th move in an N-disk Hanoi problem using a Lindenmayer system.

Solving what with what?!

towers of Hanoi

The towers of Hanoi are a puzzle in which one is asked to move disks from the rod on the left to the rod on the right according to the following rules:
  1. move only one disk at a time
  2. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  3. No disk may be placed on top of a smaller disk.
If you start with only three disks, it takes at least 7 moves to solve the problem. The wikipedia page linked above shows many ways to solve the Hanoi problem. The method I'm about to demonstrate is related to their "Binary solution" but it's different from what is described there.

Lindenmayer systems

A Lindenmayer system (or L-system as it's often called) consists of a series of symbols, called an alphabet (think: A,B,C,...) and a set of rules that transform sequences of symbols into new sequences of symbols. Here's an example:

  • alphabet A, B, C.
  • rule 1: ACB -> AB
  • rule 2: AB -> 

Rule 1 can be read as: whenever you encounter the sequence ACB, replace it with AB.
Rule 2 can be read as: given sequence AB, remove it (or: replace it with an empty string, if you like fancy words :) )

We could apply the rules to the following start sequence: ABAABCBA
  • first, use rule 2: ABAABCBA becomes  AABCBA
  • then, use rule 2: AABCBA becomes ACBA
  • then, use rule 1: ACBA becomes ABA
  • then, use rule 2: ABA becomes A
I hope by now you get the idea... L-systems have various applications, but they are best known for generating computer graphics representations of plants and trees, and various fractals (the wikipedia entry linked above has a list of interesting demonstrations). To go from a sequence of letters to a drawing, each symbol is interpreted as a drawing operation (e.g. a symbol A could mean: turn 45deg, symbol B could mean: step 1 unit forward, etc.)

How are both things related?

The following drawings show the solution of the Hanoi problem with three disks:


  • Move 1 goes from rod A to rod C
  • Move 2 goes from rod A to rod B
  • Move 3 goes from rod C to rod B
  • Move 4 goes from rod A to rod C
  • Move 5 goes from rod B to rod A
  • Move 6 goes from rod B to rod C
  • Move 7 goes from rod A to rod C
The question is: if we use 3 disks, and we want to calculate from which rod to which rod we have to move the upper disk, how can we do that? Or more general: if we use N disks, and we want to know the j-th move, can we calculate this, without actually doing all the previous moves first?

And the answer, of course, is yes we can!

Recipe

For the mathematical details of why the following recipe works, you will need to read chapter 6 in the thesis, but if you just want to apply a recipe and marvel at the wonders of science (ahem!), keep reading...

First the recipe itself, then I will illustrate using an application. If you want to calculate the j-th move (where j can go from 1 to 2^N-1) in an N-disk problem, do the following:
  1. take j and write in binary representation
  2. reverse the binary representation
  3. pad with 0's on the right side until you've used N bits
  4. remove everything coming before and including the first 1-bit
  5. Now we have a sequence of 0 and 1 which we consider the alphabet of a Lindenmayer system and we apply the following rules (in any order you like) until no more rules can be applied:
    00 -> <empty>
    11 -> <empty>
    1010 -> 01
    0101 -> 10
  6. eventually you end up with one of the following sequences. The  sequence we end up with directly tells us the j-th move in the N-disk towers of Hanoi problem:
  7. SequenceMove from to
    0A->B
    1B->C
    01B->A
    10C->B
    101C->A
    010C->A
    <empty>A->C

Example

Recall our N=3-disk Hanoi problem. Let's see if we can calculate the j=2nd move using the method shown above.
  1. take number 2 and write it in binary representation:  10
  2. reverse the binary representation: 01
  3. pad with 0's to the right until we have used N=3 bits: 010
  4. chop off everything before and including the first 1-bit:  0
  5. apply the rules until you hit one of the cases in the table: no rules can be applied here, since we are already in the case 0. According to the table, ending up with 0 indicates a move from A->B
  6. Double-checking in the solutions that were displayed before, we indeed see that the 2nd move goes from A->B.
Was this an accident, or does it really work? Lets quickly try it for all 7 moves. Each column represents a step in the recipe.
Move no.BinaryReversePadChop L-system simplifcationMove according to the table
1 1 1 10000<empty>A->C
2 10 01 01000A->B
3 11 11 1101010C->B
4 100 001 001<empty><empty>A->C
5 101 101 1010101B->A
6 110 011 01111B->C
7 111 111 11111<empty>A->C
If we take the successive moves listed in the right-most column of this table, and compare it to the solution shown before it becomes clear that the system indeed results in the correct solution (at least for the case N=3). In this case, our L-system didn't really have a lot of work to do: only twice it reduced a bit sequence. This is to be expected for low values of N (N = the number of disks used, here 3).

Example for N=5

Now let's apply the recipe to the 5-disk problem. The 5-disk problem takes (2^5-1) = 31 moves to solve.
Move no.BinaryReversePadChop L-system simplifcationMove according to the table
111100000000<empty>A->C
21001010000000A->B
3111111000100010C->B
41000010010000<empty>A->C
510110110100010001B->A
6110011011001001B->C
7111111111001100<empty>A->C
8100000010001000A->B
91001100110010001010C->B
101010010101010010010C->A
111011110111010101001B->A
1211000011001101010C->B
1311011011101100110<empty>A->C
1411100111011101100A->B
151111111111110111010C->B
16100000000100001<empty>A->C
17100011000110001000101B->A
181001001001010010011B->C
191001111001110011001<empty>A->C
201010000101001010101B->A
21101011010110101010110C->B
22101100110101101101101C->A
23101111110111101110101B->A
2411000000110001111B->C
251100110011100110011<empty>A->C
261101001011010110110A->B
27110111101111011101110C->B
2811100001110011111<empty>A->C
29111011011110111011101B->A
301111001111011111111B->C
311111111111111111111<empty>A->C

So now you can calculate the optimal move in a N-disk Hanoi puzzle with 3 poles at any moment in time without having to know any of the previous or future moves.

Order of rule application in the L-system simplifications

From the N=5 case, it becomes clear that the L-system has more work to do, and the work to be done by our L-system increases as N increases.

One thing I'd like to show you in more detail is how the order of application of the rules doesn't influence the end result. This is not as obvious as it might seem.

First consider a different L-system with the following rules:
  • alphabet: 0,1
  • rule 1: 001 -> 0
  • rule 2: 00 -> <empty>
Now start from the sequence: 001
  • If you first apply rule 1, you get 001 ->  0
  • On the other hand, if you first apply rule 2, you get 001-> 1
We ended up with 2 different results that can no longer be further simplified. Clearly, in general the order of rule application matters!

But interestingly enough, this is not the case in our towers of Hanoi move simplification L-system. While the proof is in the thesis, I will just demonstrate on a few values.

Consider the 45th move in an 9-disk problem.
  • 45 binary:  101101
  • reversed: 101101
  • padded to 9 bits: 101101000
  • chopped after first 1 bit: 01101000
The L-system is asked to simplify 01101000. It's clear that the rules can be applied in different order, but the end result is always the same move. This is not a coincidence, but a direct result of how the method works. Here are some different orders that yield the same result. No matter how hard you try, you won't find a counter-example (unless you made a calculation error ;) ).
  • 01101000 -> 001000 -> 1000 -> 10 -> move C->B
  • 01101000 -> 010100 -> 1000 -> 10 -> move C->B
  • 01101000 -> 011010 -> 0101 -> 10 -> move C->B
  • 01101000 -> 011010 -> 0010 ->  10 -> move C->B
  • ...
There you have it. L-systems solving the towers of Hanoi problem. Who would have thought ;)

Monday, July 8, 2013

Automatically create a GUI for your argparse based command line tool

Problem

You are asked to create small tool in python to help someone out. Someone else comes along who wants to reuse the tool, but needs a minor variation on the theme. No problem, you think, I'll just add a command line option using python's argparse module.

Fast forward one month. The tool proves to be a success, but everyone wanted something slightly different, leading to 15 command line options. Now people start to complain that they lose oversight over the command line options. Other people see the potential in your tool but they are afraid of command lines altogether...

You realize you could please your users by giving them a UI to set up the command line options. But creating a UI is a lot of work... What now?

Argparseui to the rescue!

If you think you may get away with a zero-effort but ugly auto-generated UI, perhaps argparseui (python2.7 and python3, GPLv3) can be of use. Argparseui depends on PyQt.

As of yet it doesn't support all of argparse, nor does it officially support python3 (although basic use cases seem to work with python3), but it seems to scratch my itch.

Example code?

 Using argparseui is very similar to using argparse. Here's an example:

Screenshot?

This is a screenshot made on Linux, IceWm. On windows, the dialog will look like a windows dialog, and on Mac OsX it should look like a Mac OsX dialog...

Sunday, April 21, 2013

Algorithmic composition with python, rtmidi, yoshimi, linuxsampler

What?

Generating real-time midi events from python!

Why?

For fun! Dabbling with python and algorithmic composition.

How?

Unpolished code available from github: Twenty five shades of random.

Eh?

Ok, ok, here's the manager's summary. Really, you should check out the code for all the details.

A score is made by scheduling activation and deactivation of score generators in time.

Score generators consist of a strategy (e.g. pick random notes and add random octaves to them, and choose random velocities, and ...) and constraints (e.g. the notes must come from a given list of allowed notes, the durations have to be a multiple of pi, ...).

There's a scheduler class that for any given time can tell you what score generators are supposed to be running or stopped. More philosophy and background information for this piece can be found on my music blog: A Touch of Music.

Youtube movie with the result of running the program once:

Each time you rerun the program, you get a different composition in a very similar style.

Creation of this piece was heaps of fun! For further experiments in algorithmic composition (if any!) I probably owe it to myself to check out in some detail the promising supercollider environment.

Thursday, November 29, 2012

Using google test with MFC applications

The problem

In order to test an MFC application with the google test framework you need a customized main function. The main function provided by the google test framework itself does not suffice as it doesn't initialize MFC properly and your application fails to start.

The solution

To solve this problem, google test allows us to create our own main function. Here's one that works-for-me. Please let me know of you come up with something more elegant.

Sunday, September 16, 2012

Variations on producer consumer in C++

Image made by Stefaan Himpe in libreoffice draw, available under CC-BY-SA license.

Problem

Paraphrased from wikipedia:
The consumer producer problem is a classical example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common buffer used as a queue. The producer's job is to generate a piece of data, put it into the buffer and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer and doing something with it) one piece at a time.
As an example consider a printer server. The printer server receives requests to print long documents. We don't want the printer server to refuse new requests while the printer is still printing. Therefore we run it in a separate thread. After receiving the request, the printer server queues it in a printer queue and immediately returns to listening for new requests. The printer server is a producer. An application monitors the printer queue and prints the requested documents, one by one. The application is a consumer.

Challenges

  • I still have too little practical experience in multithreaded programming. This article is written as part of my investigation into what is possible. If you spot mistakes or inaccuracies, please comment!
  • How do we push and pop work items on/from a queue in a multi-threaded environment?
  • If the producer is faster than the consumer, how do we prevent the queue from exploding in size, eventually filling up all available memory?
  • How can a consumer wait for data to appear on the queue?
  • How can we wait for a queue to become empty? How do we wait for a consumer to finish processing everything in its queue? What's the difference?

Preliminaries

Synchronization

In a multi-threaded environment it is imperative that we use synchronization mechanisms to avoid situations like the producer trying to add something on the queue while simultaneously the consumer tries to get something from the queue. Without synchronization mechanisms this can lead to crashes or data corruption.

Technology choices

To implement multi-threaded things in C++ in a portable way I have chosen the following technologies:
  • Boost: a C++ library that turns "C++" into "C++, batteries included"
  • CMake: a cross-platform C++ build system

CMakeLists.txt

Here's my CMakeLists.txt file (New BSD License). This file defines how CMake can find the boost libraries, and build the project.
project(ProducerConsumer)
cmake_minimum_required(VERSION 2.8)
set(Boost_MULTITHREADED TRUE)
find_package (Boost COMPONENTS system thread)
include_directories (${Boost_INCLUDE_DIRS})
link_directories (${Boost_LIBRARY_DIRS})
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES} )
To use this CMakeLists.txt file, you'd create a directory(say at: /home/user/myproject/src or c:\development\myproject\src) containing the following files
  • CMakeLists.txt (shown above)
  • main.cpp (i.e. the rest of the code appearing later in this blog entry)
Then, to build the software, you'd create a build directory outside the src directory(say at: /home/user/myproject/build or c:\development\myproject\build) and from inside that directory you'd run on the command line:
If you have gnu make installed:
cmake ../src
make
If you don't have gnu make installed on your system, try cmake --help to see how you can use it to generate a project file for eclipse, kdevelop, visual studio, ninja, codeblocks, ...

Creating a producer and consumer for testing

Here's a simple producer and consumer, both derived from a WorkerThread class (both need to run independently in a separate thread). WorkerThread implements all the things that all producers and consumers have in common, but leaves the actual work to be implemented by derived classes by means of the purely virtual method Work().
In an attempt to reduce code duplication, I've templatized the WorkerThread with a QueueType that itself is templatized with QueueContents (e.g. int or some class PrintingParameters). In the rest of this blog entry, different QueueTypes will be presented.

Attempt 1: ThreadSafeQueue

Code

This is based on the code published here.

Test program

Output

About to construct queue
About to construct producer
About to construct consumer
About to start producer
About to start consumer
Waiting for producer to finish
[PRODUCER] Produced value 0
[CONSUMER] Consumed value 0
[PRODUCER] Produced value 1
[PRODUCER] Produced value 2
[PRODUCER] Produced value 3
[PRODUCER] Produced value 4
[PRODUCER] Produced value 5
[PRODUCER] Produced value 6
[PRODUCER] Produced value 7
[PRODUCER] Produced value 8
[PRODUCER] Produced value 9
Waiting for consumer to finish
[CONSUMER] Consumption of value 0 completely handled.
[CONSUMER] Consumed value 1
[CONSUMER] Consumption of value 1 completely handled.
[CONSUMER] Consumed value 2
[CONSUMER] Consumption of value 2 completely handled.
[CONSUMER] Consumed value 3
[CONSUMER] Consumption of value 3 completely handled.
[CONSUMER] Consumed value 4
[CONSUMER] Consumption of value 4 completely handled.
[CONSUMER] Consumed value 5
[CONSUMER] Consumption of value 5 completely handled.
[CONSUMER] Consumed value 6
[CONSUMER] Consumption of value 6 completely handled.
[CONSUMER] Consumed value 7
[CONSUMER] Consumption of value 7 completely handled.
[CONSUMER] Consumed value 8
[CONSUMER] Consumption of value 8 completely handled.
[CONSUMER] Consumed value 9
[CONSUMER] Consumption of value 9 completely handled.
Queue should be empty after all threads finished: 1

Discussion

  • Each method accessing the queue first waits until it can acquire a mutex (obviously, each method has to try to acquire the same mutex). This is needed to ensure that other threads cannot modify the queue this method is operating on. This could lead to data corruption or crashes.
  • At some point (e.g. in method TryPop) we check the condition "m_queue.size()==0". If we'd replace this condition with a call to "bool Empty()", the code would deadlock. The reason is that "Empty()" tries to acquire the same mutex that "TryPop(...)" has already acquired.
  • To wait for data to appear on the queue, we wait for a condition variable. This is by far the most efficient way to wait for something to happen. In some code bases one finds constructs like "while (!DataAvailable) sleep(100);". Such approach consumes more resources and if one is not careful it is not thread-safe.
  • When the producer is faster than the consumer (which I simulated in the test program by giving the consumer a 1 ms delay, and giving the producer no delay), it will keep on pushing values on the queue, and the queue size will keep increasing. This is clearly visible in the output of the program. At some point the available memory on the system would be exhausted causing a hang up or crash. This is a serious problem that needs an improved design: a BoundedThreadSafeQueue. A BoundedThreadSafeQueue is parameterized with a maximum size. Pushing data on the queue will block until the queue has room for more entries.

Attempt 2: BoundedThreadSafeQueue

Code

Test program

Output

About to construct queue
About to construct producer
About to construct consumer
About to start producer
About to start consumer
Waiting for producer to finish
Produced value 0
Produced value 1
Produced value 2
Consumed value 0
Produced value 3
Consumed value 1
Produced value 4
Consumed value 2
Produced value 5
Consumed value 3
Produced value 6
Consumed value 4
Produced value 7
Consumed value 5
Produced value 8
Consumed value 6
Produced value 9
Waiting for consumer to finish
Consumed value 7
Consumed value 8
Consumed value 9
Queue should be empty after all threads finished: 1

Discussion

  • The test program instantiated a bounded queue with size 3, with a consumer that is slower than the producer. The output of the test program shows that the consumer first needs to consume items before pushing can proceed when the queue is full.
  • But we have a different problem now. In real life, consumption of an item will take some time (printing a large document can take several minutes). The queue can now signal that it is empty, but an empty queue does not mean that all processing is finished. (The items are removed from the queue before their processing starts.) So how can we extend our design to be able to wait until the queue and associated processing is completely finished?

Attempt 3: BoundedThreadSafeQueueSignalWorkloadDone

The basic idea is for the consumer of the queue data to inform the queue that processing the data is finished. Ideally we'd have a kind of condition variable that we can set/reset manually to signal that the queue + associated processing is completely finished (idle) or not. Someone waiting for the queue and associated processing to finish completely can then wait for the condition variable to become true. Boost doesn't offer this out of the box, but based on the code published here, it is possible to create such a manually resetable condition variable ourselves.

The consumer class needs a small update: we have to call ProcessingFinished() on the queue after finishing processing the information.

Output

[MAIN] About to construct queue
[MAIN] About to construct producer
[MAIN] About to construct consumer
[MAIN] About to start producer
[MAIN] About to start consumer
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[PRODUCER] Produced value 0
[CONSUMER] Consumed value 0
[PRODUCER] Produced value 1
[PRODUCER] Produced value 2
[PRODUCER] Produced value 3
[PRODUCER] Produced value 4
[QUEUE] Wait until idle
[QUEUE] ProcessingFinished but queue not empty. ProcessingDone flag remains low.
[CONSUMER] Consumption of value 0 completely handled.
[CONSUMER] Consumed value 1
[PRODUCER] Produced value 5
[QUEUE] ProcessingFinished but queue not empty. ProcessingDone flag remains low.
[CONSUMER] Consumption of value 1 completely handled.
[CONSUMER] Consumed value 2
[PRODUCER] Produced value 6
[QUEUE] ProcessingFinished but queue not empty. ProcessingDone flag remains low.
[CONSUMER] Consumption of value 2 completely handled.
[CONSUMER] Consumed value 3
[PRODUCER] Produced value 7
[QUEUE] ProcessingFinished but queue not empty. ProcessingDone flag remains low.
[CONSUMER] Consumption of value 3 completely handled.
[CONSUMER] Consumed value 4
[PRODUCER] Produced value 8
[QUEUE] ProcessingFinished but queue not empty. ProcessingDone flag remains low.
[CONSUMER] Consumption of value 4 completely handled.
[CONSUMER] Consumed value 5
[PRODUCER] Produced value 9
[QUEUE] ProcessingFinished but queue not empty. ProcessingDone flag remains low.
[CONSUMER] Consumption of value 5 completely handled.
[CONSUMER] Consumed value 6
[QUEUE] ProcessingFinished but queue not empty
[CONSUMER] Consumption of value 6 completely handled.
[CONSUMER] Consumed value 7
[QUEUE] ProcessingFinished but queue not empty
[CONSUMER] Consumption of value 7 completely handled.
[CONSUMER] Consumed value 8
[QUEUE] ProcessingFinished but queue not empty
[CONSUMER] Consumption of value 8 completely handled.
[CONSUMER] Consumed value 9
[CONSUMER] Consumption of value 9 completely handled.
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[QUEUE] Wait until idle
[QUEUE] Consumer is completely idle
[MAIN] Queue should be empty after all threads finished: 1
[MAIN] Waiting for producer to finish
[MAIN] Waiting for consumer to finish

Discussion

  • Writing a meaningful test program is less obvious here.
  • From the output: when the program starts, it starts producer and consumer in a separate thread, and then starts waiting in the main thread until the queue + associated processing is completely finished.
    • Just after constructing the producer and consumer, the channel is still completely idle: no work has been pushed onto the queue yet.
    • Then the producer starts producing values, and the next wait until idle blocks until the processing is completely finished. After that, WaitUntilCompletelyIdle immediately returns true (until another producer inserts work into the queue).