from candidates import *
from voters import *
from plurality import *
from borda import *
from copeland import *
from dodgson import *
from approval import *
from stv import *
from election import *
from voter_permutations import *
from voter_distr import * 
from aux import *

NUM_EXPS    = 100
NUM_ELECS   = 100
NUM_CANDS   = 5
NUM_VOTES   = 50

def generate_elections(no,c,nv,path):
    elections = []
    for i in range(0,no):
        e = generate_election(i,c,nv,path)
        elections.append(e)
    return elections        

def generate_election(no,c,nv,path):
    vs = voters(c, nv, None)
    name = path+"/blt%i.blt" % no
    vs.output_ballots(name)
    v = voters.parser(name)
    return v

if __name__ == "__main__":
    methods = ['plurality','borda','approval','even_and_equal','stv','copeland']
    com_matrix = {}
    for m in methods:
        com_matrix[m] = {}
    for m in methods:
        for n in methods:
            com_matrix[m][n] = 0

    
    for i in range(0,NUM_EXPS):
        c = candidates(None, NUM_CANDS)
        elections = generate_elections(NUM_ELECS,c,NUM_VOTES,"compare")
        
        for e in elections:
            pl = plurality(e)
            bo = borda(e)
            ap = approval(e)
            ev = approval(e,'even_and_equal')
            st = stv(e)
            co = copeland(e)
            #do = dodgson(e)

            names = [(pl,'plurality'),(bo,'borda'),(ap,'approval'),(ev,'even_and_equal'),(st,'stv'),(co,'copeland')]
            coms = []
            for i in range(0,len(names)):
                for j in range(0,len(names)):
                    coms.append([names[i],names[j]])
            for [(r1,n1),(r2,n2)] in coms:
                r1w = r1.winner()
                r2w = r2.winner()
                if r1w[0] == 'STV_tie':
                    r1w = r1w[1]
                if r2w[0] == 'STV_tie':
                    r2w = r2w[1]
                if r1w==r2w:
                    com_matrix[n1][n2] += 1

    
    vals = []
    for m in methods:
        for n in methods:
            vals.append(str(round(100*float(com_matrix[m][n])/(NUM_EXPS*NUM_ELECS),2)))

    table = """
    \\begin{tabular*}{1\\textwidth}{@{\extracolsep{\\fill}}|l|r r r r r r |}
    \hline
    & Plurality & Borda & Approval & Even & STV & Copeland\\\\
    \hline
    Plurality & %s & %s & %s & %s & %s & %s \\\\
    Borda &  %s & %s & %s & %s & %s & %s \\\\
    Approval & %s & %s & %s & %s & %s & %s \\\\
    Even & %s & %s & %s & %s & %s & %s \\\\
    STV & %s & %s & %s & %s & %s & %s \\\\
    Copeland & %s & %s & %s & %s & %s & %s \\\\
    \hline
    \end{tabular*}
    """
    nrs = tuple(vals)
    print table % nrs

