A collection of sloppy snippets for scientific computing and data visualization in Python.

Monday, March 18, 2013

Binary Plots

A binary plot of an integer sequence is a plot of the binary representations of successive terms where each term is represented as a sequence of bits with 1s colored black and 0s colored white. Then each representation is stacked to form a table where each entry represents a bit in the sequence.
To make a binary plot of a sequence we need to convert each term of the sequence into its binary representation. Then we have to put this representation in a form which make us able to build the plot easily. The following function converts the sequence in a matrix where the element i-j represents is the bit j of the element i of the sequence:

from numpy import zeros,uint8
from pylab import imshow,subplot,show
def seq_to_bitmatrix(s):
""" Returns a matrix where the row i
is the binary representation of s[i]
s must be a list of integers (also long) """
# maximum number of bits used in this sequence
maxbit = len(bin(max(s)))
M = zeros((len(s),maxbit),dtype=uint8)
for i,e in enumerate(s):
bits = bin(e)[2:] # bin() -> 0b100, we drop 2 chars
for j,b in enumerate(bits):
M[i,maxbit-len(bits)+j] = int(b) # fill the matrix
return M

The matrix returned by the function above represent each bit with an integer. Of course, this is a waste of space but makes us able to use the function imshow in order to draw the binary plot:

From this graph we can observe two interesting things. The first is that we need more than 1200 bits to represent the biggest number of the sequence we generated, which is 199!, and the second is that when n grows the bits on the right tend to be unused.
Let's see what happen with the famous Fibonacci sequence:

In the snippet above we compute the first 149 Fibonacci numbers using memoization then we plotted the sequence in the same way of the factorial. This time the result is surprising:

Indeed, it is very interesting to observe that the graph reveals a fractal like pattern of hollow and filled triangles.
Another sequence that shows a fractal like series of patter is the sum of the first n natural numbers which we can plot as follows:

In this case the Gauss formula have been used to compute the terms of the sequence and this is the result:

This time the matrix have been transposed to have a vertical visualization. We have that each column is a binary representation of a term of the sequence.
In conclusion, we plot the sequence np for p = 1,2,3,4: