#!/usr/bin/env python

# Used in Generating the char in (2010-02-26)
# http://www.potreroboosters.org/profiles/blogs/rebuild-potrero-development

import pylab as P
from pprint import pprint as pp; from StringIO import StringIO as sio
import string

DATA = """
Dagget Triangle	 22,264 	 5.50 	400	 72.7
888 7th St	 13,600 	 3.36 	224	 66.7
1130 Mariposa St	 1,440 	 0.36 	21	 59.0
The Potrero	 12,070 	 2.98 	164	 55.0
Esprit Park	 11,256 	 2.78 	142	 51.1
Potrero Court	 11,928 	 2.95 	132	 44.8
Missouri & 16th	 2,928 	 0.72 	32	 44.2
Sierra Height	 6,552 	 1.62 	66	 40.8
Potrero Square Lofts	 5,670 	 1.40 	57	 40.7
Victoria Mews	 12,212 	 3.02 	88	 29.2
"""

DATA_P = """Rebuild Potrero	 148,122 	 36.60 	1550	 42.3"""

class Item(object):

    def __init__(self, line):
        parts = line.split()
        p = line.split('\t')
        self.name = p[0]
        self.area = float(p[2])
        self.unit = int(p[3])
        self.density = float(self.unit) /self.area

    def __repr__(self):
        return str(self)

    def __str__(self):
        return '%s %s arce %s unit' % (
            self.name,
            self.area,
            self.unit,
        )


def parse():
    d = DATA.replace(',','')
    lines = filter(None, d.splitlines())
    data = [Item(line) for line in lines]
    return data

patches = None

def main():

    global patches

    data = parse()
    total_area = sum(it.area for it in data)

    P.figure()

    rebuild = Item(DATA_P)
    n, bins, patches = P.hist([rebuild.area/2], [0,rebuild.area], weights=[rebuild.density], histtype='bar', rwidth=1, facecolor="#996633")

    r = patches[0]
    P.text(r.get_width()-1, r.get_height()-3,
        rebuild.name,
        horizontalalignment='right',
        verticalalignment='top',
        )

    x = []
    bin_cum  = 0
    bins = [0]
    weights = []

    for it in data:
        x.append(bin_cum+it.area/2)
        bin_cum += it.area
        bins.append(bin_cum)
        weights.append(it.density)

    max_size = 36.6

    bins.append(99)

    n, bins, patches = P.hist(x, bins, weights=weights, histtype='bar', rwidth=0.9, facecolor="#00cc00")

    for r, it in zip(patches, data):
        if r.get_width() > 1:
            P.text(r.get_x()+0.3, r.get_height()-1,
                it.name,
                rotation=270,
                horizontalalignment='left',
                verticalalignment='top',
                )
        else:
            P.text(r.get_x()+0, 2,
                it.name,
                rotation=270,
                horizontalalignment='left',
                verticalalignment='bottom',
                )

    P.xlabel('Area (acre)')
    P.ylabel('Density (unit/acre)')
    P.title(r'Potrero Hill Residential Development')
    P.axis([0, 38, 0, 75])

    P.show()

    return data


if __name__ == '__main__':
    main()


