#!/usr/bin/python
from string import atoi
from numarray import zeros


n = 5

'''
Republic Of China Students Association
Taiwan Graduate Students Association
Taiwanese Graduate Students Association
Taiwan, Republic Of China Students Association
25N121E
'''

abbrev = ['ROCSA','TGSA','TsGSA','TROCSA','25N121E']
 
def main():

    data = file('votes/BALLOTS').readlines()
    ballots = []
    for line in data:
        if line == '\n':
            continue
        line = line.split(']')[0]
        line = line.replace('[','')
        line = line.split(',')
        ballots.append([])
        for item in line:
            ballots[-1].append(atoi(item.strip()))

    Nvotes = len(ballots)
    condorcet(ballots,Nvotes)

    return

    print "Instant Runoff analysis:"
    cands = irv(ballots)
    for i in range(1,n):
        cands = irv(ballots,cands)

def irv(ballots,cands = [i for i in range(n)]):

    losers =[]
    m = len(cands)
    for round in range(m-1):

#        print "Round %s" % (round+1)

        votecount = {}
        for cand in cands:
            votecount[cand] = 0.

        for ballot in ballots:
            for i in range(n):
                winners = [j for j in cands if ballot[j] == i+1]
                if winners != []:
                    break
            for winner in winners:
                votecount[winner] += 1./len(winners)

        for name in cands:
            print "%12s %s" % (abbrev[name], votecount[name])

        least = min([votecount[cand] for cand in cands])
        loser = [i for i in cands if votecount[i] == least][0]
        loser_index = [i for i in range(len(cands)) if cands[i] == loser][0]

        losers.append(loser)

        print "Eliminate: %s" % abbrev[loser]

        cands.pop(loser_index)

    print "             Winner: ", abbrev[cands[0]]
    return losers

def condorcet(ballots,Nvotes=0):

    print "Pairwise (Condorcet) Analysis:"

    winmat = zeros((n,n),'l')

    for ballot in ballots:
        for j in range(n):
            for k in range(n):
                if ballot[j]<ballot[k]:
                    winmat[j,k] += 1

    print_winmat(winmat)


    if Nvotes:
        print_winmat(winmat,Nvotes)


    for i in range(n):
        for j in range(i,n):
            winmat[i,j] -= winmat[j,i]
            winmat[j,i] =- winmat[i,j]

    print_winmat(winmat)

def print_winmat(winmat,Nvotes=0):
    print "%8s" % '#',
    for i in range(n):
        print "%8s" % abbrev[i],
    print
    for i in range(n):
        print "%8s" % abbrev[i],
        for j in range(n):
            if i == j:
                print "%8s" % "X",
            elif Nvotes:
                print "%7.1f%%" % (winmat[i,j]*100./Nvotes),
            else:
                print "%8i" % winmat[i,j],
        print
    print



main()

