Thursday, July 8, 2010

How much do you cost me?

Introduction

Study of algorithms and data structures is a major field in computer science. Efficiently representing and processing data has been of paramount importance since the early days of computing. Many problems are simply not accessible without proper study, since the computational complexity used to overwhelm older machines.

Today, we have powerful machines. Tomorrow, we will have more powerful and “more parallel” machines. One day, our computers will surpass the computing power of our own brain. However, no matters how fast the computer it is, there are always problems which are too hard, too expensive and, in short, intractable.

Essentially, the cost of the algorithm depends from the size of its input. For example, searching for an element in a list intuitively takes time proportional to the number of elements: after all, we don’t know where it is, we have to start somewhere and the element could be at the other end of the list.

In this case we say that the worst case is exactly A∙N, if A is the cost of comparing two elements and N is the length of the list. The average case is “only” A∙(N/2) since “in average” the element will be found after examining only half of the elements. Intuitively, the probability the element is the last one, is equal to the probability it is the first one, and so one. Computing average case cost is usually harder than worst case cost, because involves probability and random variables.

Landau notation and estimates

The computational cost of algorithms is usually represented in a unified notation (called Landau notation, from the name of the famous mathematician who introduced the notation in the field of calculus). Essentially, we don’t care about the multiplicative constants in the costs (e.g., A, “the cost of comparing two elements”) as long as they are, well… constants. We usually say that an looking for an element in a list costs O(N), which means that the time is proportional to the size of the list itself.

Most of the times, computing the cost of an algorithm is rather straightforward. Considering a strictly imperative setting, you essentially estimate the number of times you run the body of a loop. For example, let us consider
the following code:

M = {}
n = 4

for i in xrange(0, n):
    for j in xrange(0, i):
        M[i,j] = M[j,i] = i + j

print M

It is rather easy to see that if A is the cost of M[i,j] = M[j,i] = i + j, the whole thing costs (using presumed Gauss's formula):



That is to say it's O(N^2). A (correct) but coarse argument is that the internal loop runs i times, and i is at most n. So in the worse case it is n. The upper bound is used as an estimate n*n (again O(n*n)).

Things are not always that easy: sometimes the worse case is completely uninteresting. E.g., the most widely used simplex algorithm[0] has an exponential worse case cost. Exponential means that it essentially sucks. 2^1000 is a huge[1] number and 1000 is not an extremely huge input size. In pratice, the simplex algorithm is used, since the average complexity is polynomial. There is still active research on the estimation of the complexity of that algorithm.

The Master Theorem

A large class of algorithms are called "divide et impera"; a typical example is mergesort[2]. Here a trivial python implementation is given:

def merge_sort(L):
    if len(L) <= 1:
        return L
    else:
        middle = len(L) / 2
        left = merge_sort(L[:middle])
        right = merge_sort(L[middle:])
        return merge(left, right)

def merge(left, right):
    i = j = 0
    max_i = len(left)
    max_j = len(right)
    sorted_ = []
    while i < max_i and j < max_j:
        if left[i] < right[j]:
            sorted_.append(left[i])
            i += 1
        else:
            sorted_.append(right[j])
            j += 1
    if i < max_i:
        sorted_.extend(left[i:])
    else:
        sorted_.extend(right[j:])
    return sorted_
Of course, no Python user would use such functions. They use recursion instead of iteration, they are not particularly efficient, the "Timsort"[3] implemented in the Python library is far more efficient both algorithmically and code-wise. Algorithm books tell us that merge-sort has worse and average case O(N log N). As with most divide et impera algorithms, the result can be proved with ad hoc demostrations. However, I found extremely useful using the so-called master theorem[4]. This is essentially a swiss-knife result that gives us the complexity of an algorithm given the way the data is "divided" and "recomposed" (to rule, of course!). The complexity of the algorithm on an input of size n is T(n). f(n) is the cost done outside the recursive calls (e.g., the time needed to decompose and put together the data); a is the number of subproblems in the recursion and n/b is the size of the input of the subproblems. For example, in merge-sort a = 2 and b = 2. f(n) is proportional to the size of the input vector. The master theorem states that if:


The big theta notation essentially says that the specified bound is asymptotically both a lower and an upper bound. The big omega means that the specified bound is a lower bound.

Notes

[0] http://en.wikipedia.org/wiki/Simplex_algorithm
[1] 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
[2] http://en.wikipedia.org/wiki/Merge_sort [3] http://bugs.python.org/file4451/timsort.txt
[4] Introduction to Algorithms; Cormen, Leiserson, Rivest, and Stein; MIT Press

More on Word

Some pieces of software are unbelievable: as soon as you start noticing how nice are certain features, you discover that some other parts are so incredibly broken that you would want to put the whole thing in the thrash.

As is customary, I received the template to format my article, which was an IEEE standard. Nice. I opened it in Word 2007 for Mac (and the template should be compatible with that) and I removed the contents of the template (as advised on the template itself) and filled with my own text. Shit happens.

For no good reason, the styles built in the template were imported utterly broken. For example the base font size was plainly wrong, some styles did not use the “keep together with next paragraph” thing and so on. Essentially, I had to manually check the styles I used with ones in the unmodified template in order to fix things. And I was able to, however, it took time.

Then I sent the file to my advisor (as a word file, since perhaps he would like to modify some parts). And he told me I was not following the standards, for example because the image labels did not start with “Figure x.”; I found this quite strange, since I was pleasantly surprised by the fact that the text was auto-inserted choosing the style (I think as a kind of numerated list style). I checked my file and the figure x. was still there. So I opened the document with word for Windows. And the Figure x. was missing.

Apparently Office 2008 for Mac and Office 2007 for Windows are not compatible at all. The question is: how many things are going to be fucked up? If I got a lot of nice features which I can’t use because otherwise I can’t share files with colleagues, then the whole point of using Word instead of Latex (and especially the “revisions” feature, which is very useful) is lost.

As a nice side note, I discovered the bibliography IEEE style I downloaded to “auto-manage” the bibliography is utterly broken. First, the references like [4] have italic numbers and the standard I have to follow has not… perhaps there are multiple standards, but then… how to discover the right file?

Second the bibliography itself is formatted as a huge double column table, which is completely unusable in 2-column mode. Other styles (such as the ones built-in with Word) do not format the references, so essentially applying the “references” style to the unformatted references simply solves the problem. But not with the style I have to use. And I don’t understand why word does not come with such widely used styles and I have to download broken third party implementations. The solution was to format the references by hand. Besides, Papers “import into Word” feature also gave me some problems, as every single link contained the pdf url, even if that is not standard. I don’t understand if it’s Papers fault, Word fault or the style fault. Well… doing things by hand, I solved the problem.

I still don’t understand the part “Word is user friendly”.

Thursday, June 24, 2010

Portable pleasure

This spring, I got convinced I needed a netbook. Essentially, I'm a satisfied Apple user (mostly). However, I needed a portable machine to work with. Work means coding. No code, no work. Moreover, I was curious of the new Windows 7 operating system and I also wanted to check Linux progresses as a desktop OS. I don't consider myself an Apple zealot: no Apple netbook, does not mean no netbook at all. I think Virtual Machines are a great tool. However, I don't really relate with virtual os's. I don't customize them. I just use them in order to perform some given tasks (e.g., testing). I thought that using Linux and Windows as primary operating systems when I only had the netbook was a great way to try them. I was pretty sure I could work with Linux (and I was confident I could overcome every installation issue that would have faced). I bought an Asus EEE 1005PE with 14h of autonomy declared. Other specs were completely uninteresting to me. CPU, RAM. I didn't give a fuck. If I need power, I've got a Mac Pro. If I need portable power, I have a Mac Book Pro. The EEE has plenty of HD space, and comes already partitioned (which means installing Linux is easy and you retain the EEE auto-reinstal clean windows capabilities). Should I need more ram, I could buy it. Ubuntu 10.4 is a pleasant surprise: I have never seen such a nice DE in a non Apple OS. The desktop is nice, the apps work great. NetworkManager does not suck anymore, some Ubuntu specific apps are very nice. It is rather pleasurable to work with (even if I don't use the netbook remix variant). Of course, some apps are completely lacking. However, I need it to code, write docs, email, browse... chat. Good. Windows was both a nice surprise and a disappointment. Compared to other MS OS's it is a nice surprise. It is fast, small, easy to use. Compared to what I read about Windows 7 it is a delusion: I think that Ubuntu is way nicer. However, I need some MS applications and that's it. With a little bit of work I installed everything I needed and I have got a nice working system. Unfortunately, Windows seems to slow down progressively and I don't understand why (I stopped installing stuff, I don't think that could be the cause). Hardware support is excellent both with Windows and with Ubuntu. Battery life lasts longer with Windows. I think about 12 hours of effective light work, wireless on. Ubuntu is probably around 9, which is sufficient for my goals.

Location:Via Montebello,Parma,Italy

Monday, June 21, 2010

The power of the power of the power...

Though I really don’t particularly like writing about hardware in my blog, I provide some updates on my current hardware situation. Some years ago, I wrote a short series of blog posts about my iMac. That was a first series machine and I criticized lack of support for scientific software. This is partly related to GMP not being too much collaborative (as it appears they did not have intel macs, bac in the day).

Of course those problems have been entirely solved quite soon. I suppose that by the end of the year they were no more and the faster intel chips were just the right choice for everyone. A couple of years after those events I bought a MacBook Pro 15” laptop and that became my main work machine. Among the things I really liked best about the intel processor (and all the lovely virtualization software packets out there) was that I could run Linux in a virtual machine. Since I did not stop working on a certain “almost-linux-only” project, that was really good (and saved me from ugly partitioning). Although I had a Parallels license (which I used on the iMac), I preferred to use the simpler VirtualBox. Back in the day, Parallels did not support Linux exceptionally well and I could just live with the free VB. And that is the machine I used (along with the iMac) for my M.Sc. dissertation.

4 years after i first turned it on, my iMac blew off. Well, not literally. I suppose I can fix it, however, I chose to buy a new Mac. This time it is a MacPro. Essentially, I hated that if I thrashed my iMac (because of other damages) I could not save the monitor. So I chose a monitor-less computer. Essentially the thing is powerful. It is extremely evident when encoding my CDs into mp3’s. I don’t do much video editing.

Nonetheless, Parallels is completely capable of sucking all the resources. I had to stop using it, since the MP became useless. I suppose it may be related to having only 3 GB, even though the iMac had only 2. If I will need a virtualization software, I suppose I’ll go with VMWare or VirtualBox. But… that is not the last machine I bought.

Glad I chose Blogger

This new command line thing is awesome.

Probably I would have regretted if I chose another blog service.
This also makes me think writing the crappy little blogging application for Linux should be pretty easy. :)

Sunday, June 13, 2010

Prolog Homoiconicity

Although when talking about homoiconicity the first language that springs into mind is Lisp (or a Lisp dialect), Prolog is a completely homoiconic language. In Prolog everything is a term. Variables, atoms, numbers are terms. And everything else is a compound term: e.g., foo(a, b) is a term. Lists are the main data structure of Prolog, and a list is a term as well. In fact a Prolog list is i) the empty list []; ii) a term '.'(a, b), where a is a term and b is a list or a variable. We say that a compound term foo(x, y) has functor foo and arity 2. Clauses (the prolog equivalent of "functions") are represented as terms whose main functor is :-, their head is a prolog term and their body is a prolog term as well. Moreover, the read predicate reads from file (or standard input) some prolog predicates. E.g., this simple Prolog program reads a Prolog program into memory (and the program is represented as a list of prolog terms):
read_all([Predicate|T]) :-
	read(Predicate),
	Predicate \== end_of_file, !,
	read_all(T).
read_all([]).

read_file(File, L) :-
	see(File), read_all(L), seen.
If we call read_file to read "read_file.pl" (spaces added by me):
?- read_file('read_all.pl', L).
L = [(read_all([_A|_B]):-read(_A),_A\==end_of_file,!,read_all(_B)),
     read_all([]),
     (read_file(_C,_D):-see(_C),read_all(_D),seen)] ? y
The display predicate some prolog interpreters provide gives us more insight on internal representation of terms. We call it on just one rule in order not to clutter the output with list representations:
?- read_file('read_all.pl', [H|_]), display(H).
:-(read_all(.(_932,_952)),,(read(_932),,(\==(_932,end_of_file),,(!,read_all(_952)))))
And here on the full program (notice... lists are "consed" with the '.' functor):
?- read_file('read_all.pl', L), display(L).
.(:-(read_all(.(_900,_920)),,(read(_900),,(\==(_900,end_of_file),,(!,read_all(_920))))),.(read_all([]),.(:-(read_file(_1410,_1430),,(see(_1410),,(read_all(_1430),seen))),[])))
Indeed, infix operators have been placed in prefix form like every other predicate (indeed, they are not special, just a parsing trick). Another "useful" predicate (not standard) is portray_clause/1, in order to do some "pretty-printing":
?- read_file('read_all.pl', [H|_]), portray_clause(H).
read_all([A|B]) :-
        read(A),
        A\==end_of_file, !,
        read_all(B).

The assert family of predicates can “store” into the Prolog database facts (this is very common, in fact, memoization is often implemented this way) and rules (this is done less frequently – and there may be a slight efficiency penality [CHECK]). Thus we can manipulate terms (indeed that is what Prolog is about) and load them as programs. Notice that I showed the read predicate only to show that “standard” Prolog programs are represented that way, but it is not necessary at all to use programs saved in files.

4 ?- assert((foo(X) :- bar(X), \+ baz(X))).
true.

5 ?- assert(bar(1)), assert(bar(2)), assert(baz(2)).
true.

6 ?- foo(X).
X = 1 .

Monday, June 7, 2010

PDF and other tragicomical histories

Today I had the unlucky task of creating a PDF from a Word document we wrote.
In fact, I did not think the thing would have gotten tricky (ah, how naive!). Word 2007 has a nice "save to PDF" menu item and I thought I could use that to solve my problem. Luckily enough, I double checked the generated PDF on the Mac. And, apparently, all the bold fonts were substituted with another font. I already mentioned this in a post earlier today.

This is completely illogical since the font was Times New Roman and I have Word on the Mac as well, which would install a lot of additional fonts, even if TNR was not that standard. So I searched for a Windows PDF creator (which, by the way both OS X and Linux-based desktop programs have). I found a bunch of them, some commercial, some free, some open source. My choice was PDFCreator.

Some reasons are: i) it is free as in free beer, ii) it is free as in free speech, iii) had no ads, iv) is based on the same softwares I happily used with Linux. Of course, reason i) was paramount: I had no intention to buy a stinking PDF creator for Windows unless it is absolutely necessary (which may be). The other three reasons have to be considered together: I searched google for suggestions, but I had no clue on which one was supposed to be better.

Usually the only problem with open source software is lack of support/user friendliness. However, that was not the case of PDFCreator. Unfortunately, for reasons beyond my comprehension, the generated pdf completely screws[0] a TIFF picture I put in the document. The same picture is perfectly fine in the PDF generated with word built-in generator. I tried to include in word a PDF, but that did not work either (the PDF was linked, but not visible -- nor printable --). Amazingly, Word for Mac is capable of using PDF image files, IIRC.

Perhaps, I should have tried more generators. I went home, opened Word for Mac, double checked that the formatting was fine (which was not, but I could fix it in little time) and simply printed to PDF. The PDF is perfect. This goes under: how to completely waste a Monday morning.

Footnotes

[0] This is a technical term, essentially it looked like it had low resolution

A matter of homoiconicity

Somewhere around the late sixties the term “homoiconicity” has been introduced in the computer science community. In fact, the term was older and dates to the 1960, at least according to Wikipedia. Strangely enough, I did not find traces of the term homoiconic or homoiconicity in McIllroy [1]. I was not unable to recover the full text of the paper on TRAC [2]. However, widespread use of the term is due to McKay (along for the very idea of object oriented programming and a good deal of criticism on Lisp – perhaps I will look for some opinions of famous lispers on Smalltalk to make things even) in his Ph.D. dissertation.
The basic idea is simple: program is data. That is to say, the program is represented in the very same format as data. Thus, a program can manipulate programs (and even itself) in the same ways it uses for data. This is great and is the foundation for great and funny meta-programming.
Indeed, references on TRAC should make clear that a structured representation of programs is not needed. TRAC manipulated strings and programs where represented as strings. On the other hand, Lisp manipulates lists and a program is a list. It is quite rare in a discussion on programming languages with a lisper that he does not use the term “homoiconic” somewhere in the discussion, usually before becoming condescending (a proof of this is being developed actively – no trolls have been harmed during the experimentations).
What I find extremely interesting is that this great property was simply obvious in theoretical models. Universal Turing Machines and primitive functions need an enumeration of programs (functions, respectively) in order to manipulate such objects. If such enumeration was not possible, most computer science would not have been created.

The von Neumann architecture also relies heavily on instructions being represented as numbers and stored along with data. It’s a bit of a pity that this properties have not been naturally ported to programming languages (except from Lisp and some others).
Indeed, we all agree that homoiconicity is a great property in programming languages. In fact, I often find frustrating complete lack of it (e.g., Java is completely not homoiconic, since its main data structure is the Object but Java programs are not even near to being objects – ok, you can always call the compiler get an AST… but this is not what the whole thing is about). Other languages have limited support for it.
In Python functions and classes (and objects) are available when compiling a module. The whole decorator concept, for example, relies on the fact that functions are objects and can be passed as such at compile time. Very powerful meta-programming techniques in Python rely on “program” manipulation, where programs are represented as classes and functions (and not syntactically, like in Lisp). This makes some kind of manipulation very hard (without resorting to byte-code manipulation – and then the same objection with the java compiler/AST thing applies – or to basic string manipulation, which I would not consider as a symptom of homoiconicity, since strings are not “the main data” in Python). However, I would not rule Python out of the bunch of homoiconic languages, either. Perhaps “partially homoiconic” applies? Or perhaps do we need better built in tools to manipulate classes and functions in Python to qualify for the full homoiconic(tm) certification from old lisp hackers[3]?

References

  1. McIlroy, M. D. 1960. Macro instruction extensions of compiler languages. Commun. ACM 3, 4 (Apr. 1960), 214-220. DOI
  2. MOOERS, C.N. TRAC, a text handling language. Proc. ACM 20th Nat. Conf. Cleveland, Aug. 1965, pp. 229-246.
  3. Not meant to be offensive… perhaps old could be replaced with ancient?

Using word to write...

Using word to write articles is a rather perverted art. E.g., why are the "regular expression" different from every other syntax I met and there are two different syntaxes depending whether you are using jolly characters or not?

Why is the bibliographic tools such a joke that almost everybody does it by hand (and, moreover, many conferences explicitly tell you to do it by hand? and the W2007 implementation is not compatible with W2003 – at least that is the opinion of W2007 on that matter)

And using images is a PITA. But that is a PITA with Latex as well. Last but not least, I have yet to understand why a PDF created with word for windows visualize bold characters (I'm following the IEEE template, so changing the font is not an option... besides, it's times new roman) with a *different* non-bold font when opened on the Mac. If it were not such a standard font I would have said it's a matter of not including the font.

Thursday, June 3, 2010

Yet another C++ unit-testing library (nano-unit++)

http://bitbucket.org/rik0/nano-unit/
Goals: be easy to use, be easy to install
Right now, it does less than needed. However, I plan to add features as I need them. Besides, I want to make it as DRY as C++ allows, even at the cost of fighting with template metaprogramming.
However, I hope I won't need boost, as it would be a rather important and expensive dependency.