from voters import *

class copeland():
    voters = None
    candidates = None
    cond_comp = None
    num_cands = None
    ALPHA = None

    def __init__(self, voters, ALPHA=0.5):
        """
        Calculates the Copeland winner, which uses a voting rule which satisfies
        the Condorcet criterion.  The winner should win in pairwise comparison
        with all other candidates.
        """
        self.voters = voters
        self.candidates = voters.cands.candidates
        self.cond_comp = {}
        self.scores = {}
        self.num_cands = len(self.candidates)
        self.ALPHA = ALPHA

    def __str__(self):
        w = self.winner()
        if len(w) == 1:
            return "Copeland winner: %s" % w
        else:
            return "Copeland tie: %s" % w

    def condorcet_compare(self):
        for c1 in self.candidates:
            self.cond_comp[c1] = {}
            for c2 in self.candidates:
                self.cond_comp[c1][c2] = 0 #a matrix of candidates x candidates
                for voter in self.voters.votes:
                    s1 = 0
                    s2 = 0
                    for i in range(0, self.num_cands):
                        #check if the candidate is a pairwise winner
                        if voter.ballot[i] == c1:
                            s1 = i
                        if voter.ballot[i] == c2:
                            s2 = i
                    if s1 < s2: #if the index is lower, the score is higher
                        self.cond_comp[c1][c2] += 1

    def score(self):
        """
        Uses the pairwise comparisons from score()
        """
        self.condorcet_compare()
        for c in self.candidates:
            self.scores[c] = 0
        for c1 in self.cond_comp:
            for c2 in self.cond_comp[c1]:
                if self.cond_comp[c1][c2] > self.cond_comp[c2][c1]:
                    self.scores[c1] += 1
                else:
                    if self.cond_comp[c1][c2] == self.cond_comp [c2][c1] and c1 != c2:
                        self.scores[c1] += self.ALPHA * 1
        return self.scores
        
        
        
    def winner(self):
        self.score()
        top = []
        val = 0
        #print "Copeland:"
        #print self.scores
        for v in self.scores.itervalues():
            if v > val:
                val = v
        for k,v in self.scores.iteritems():
            if v == val:
                top.append(k)
        return top

