#!/usr/bin/env python

from __future__ import division

import StringIO

import numpy

def allIncomes(x,I):
  z = []
  for j,x in zip(x,I): z.extend([x]*j)
  return z

def gini(x):
  "this will fail for perfect inequality"
  def lorenz(x):
    s = sum(x)
    return [0] + [ sum(x[:i+1])/s for i in xrange(len(x)) ]
  def area(l):
    n = len(l)-1
    return sum((1/n)*((l[i-1]+l[i])/2) for i in xrange(1,len(l)))
  return 1 - 2*area(lorenz(sorted(x)))

def makeTable(*args):
  """returns file-like object containing space delimited table
  args should be ('header', [list, of, data])"""
  s = StringIO.StringIO()
  c = ['A', 'B', 'C', 'D', 'E']
  head = [x[0] for x in args]
  data = [x[1] for x in args]
  print >> s, '', # empty cell, top left
  for i in head: print >> s, i,
  print >> s
  for j,i in enumerate(c):
    print >> s, i,
    for x in data: 
      if isinstance(x[j], float): print >> s, "%0.2f" % x[j],
      else: print >> s, x[j],
    print >> s
  s.seek(0)
  return s

def table2Html(s):
  "converts space/newline delimited table to html"
  x = ['<table border="1">\n']
  app = x.append
  for i, line in enumerate(s.readlines()):
    if i == 0: cell='th'
    else: cell='td'
    app("  <tr>")
    for element in line.split(' '):
      app("<%s>%s</%s>" % (cell, element, cell))
    app("</tr>\n")
  app('</table>\n')
  return ''.join(x)

# counts from graphs #
A = (19, 1, 1, 1, 1, 1, 3)
B = (13, 11, 9, 7, 5, 3, 1)
C = (7, 11, 9, 7, 5, 3, 1)
D = (1, 3, 7, 11, 7, 3, 1)
E = (1, 3, 5, 7, 9, 11, 7)
World = (A, B, C, D, E)

if __name__ == "__main__"

  tables = [] #we'll print these later

  ## Various income assumptions
  for I in [(10,20,30,40,50), (1,10,100,1000,10000)]:
    # Population assumptions
    ## population multiplier
    # M = 1 
    # M cancels out in all relevant measures (obviously not POP and Gi(GDP))
    for M in (1,):
      W = [[y*M for y in x] for x in World]
      POP = [ sum(x) for x in W ]
      Gii = [ allIncomes(x,I) for x in W ]
      Gi = [ sum(i) for i in Gii ]
      GiCap = [ i/j for i,j in zip(Gi,POP) ]
      Median = [ numpy.median(x) for x in Gii ]
      Gini = [gini(x) for x in Gii]
      tables.append(makeTable( ('Pop',POP),('GDP', Gi), ('GDP/C', GiCap), ('Median', Median), ('Gini', Gini)))
  
  for i in tables:
    # get table as space separated
    #print i.getvalue()
    print 
    # if you do the above and the below, you'll need to seek to the beginning
    # i.seek(0) 
    print table2Html(i)
