
#!/usr/bin/python

from pylab import *

y_gap = 0.4
x_gap = 0.05

def plot_sequence (t, c, g, labels):

    t = array(t, dtype=float)
    c = array(c, dtype=float)
    g = array(g, dtype=float)
    labels = array(labels)

    n_rows = len(c)
    n_cycles = t.shape[1]

    y = y_gap/2
    yy = zeros(len(c))
    for i in xrange(n_rows):
        yy[i] = y
        y += c[i] + y_gap + g[i]

    figure(figsize=(7,4.3))
           
    for i in xrange(n_rows):
        excess = 0.0
        for j in xrange(n_cycles):
            start = excess + x_gap
            stop = excess + t[i,j]
            excess = max(stop-1, 0)
            stop -= x_gap
            if stop < start:
                start = (stop+start)/2.0 - x_gap/4.0
                barh(yy[i],
                     x_gap/2.0,
                     height = c[i],
                     left = j + start,
                     color = 'k')
            else:
                if start <= 1:
                    barh(yy[i],
                         min(stop,1)-start,
                         height = c[i],
                         left = j + start,
                         color = 'g')
                    start = 1
                if start <= 2 and \
                   stop >= start:
                    barh(yy[i],
                         min(stop,2)-start,
                         height = c[i],
                         left = j + start,
                         color = 'y')
                    start = 2
                if stop >= start:
                    barh(yy[i],
                         stop-start,
                         height = c[i],
                         left = j + start,
                         color = 'r')

    yticks(yy+c/2., labels)
    for i in range(1,n_cycles):
        axvline(i, linestyle=':')
    ylim ((0,y-y_gap/2))
    
a = 1.5
b = 0.0
c = 1.5
d = 0.0
plot_sequence([[a,a,b,b,a,a,b,b,a,a,b,b],
               [c,d,d,c,d,d,c,d,d,c,d,d]],
              [2,2], [0,0],
              ['A','B'])

savefig('timing.png')
show()
