Example #1
0
def csv_from_stv_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow

        make_csv_intro(writerow, election, lang)
        actions_desc = {
            'elect': _('Elect'),
            'eliminate': _('Eliminated'),
            'quota': _('Eliminated due to quota restriction')
        }
        from stv.parser import STVParser
        for poll in polls:
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            results_winners = poll.stv_results[0]
            results_all = poll.stv_results[1]
            result_steps = poll.stv_results[2]
            stv = STVParser(result_steps)
            rounds = list(stv.rounds())
            writerow([])
            writerow([strforce(_("Elected")), strforce(_("Departments"))])
            for winner_data in results_winners:
                winner_id = winner_data[0]
                winner = indexed_cands[str(winner_id)]
                winner = winner.split(':')
                winner_name = winner[0]
                winner_department = winner[1]
                writerow([strforce(winner_name), strforce(winner_department)])
            for num, round in rounds:
                round_name = _('Round ')
                round_name += str(num)
                writerow([])
                writerow([strforce(round_name)])
                writerow([strforce(_('Candidate')), strforce(_('Votes')),\
                    strforce(_('Draw')), strforce(_('Action'))])
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    writerow([strforce(cand_name),strforce(votes),\
                    strforce(draw), strforce(action)])
Example #2
0
    def make_output(self, filename):
        data = self.csvData + self.objectData
        keys = ('inst', 'nr_voters', 'nr_voters_voted', 'start',
                'end', 'uuid', 'election_name', 'nr_polls', 'admin', 'official')

        fd = filename
        close = False
        if isinstance(filename, basestring):
            fd = open("{}.csv".format(filename), 'wb')
            close = True

        writer = csv.writer(fd, delimiter=',')
        head_row = map(lambda c: c.encode('utf-8'), self.header)
        writer.writerow(head_row)
        for row in data:
            writer.writerow([row[k].encode('utf-8') if type(row[k]) != int
                            else row[k] for k in keys])
        if close:
            fd.close()
Example #3
0
def csv_from_preference_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow

        make_csv_intro(writerow, election, lang)
        for poll in polls:
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            writerow([strforce(_("Candidates"))])
            for item in questions[0]['answers']:
                writerow([strforce(item)])

            writerow([])
            writerow([])
            writerow([
                strforce(_("Candidate")),
                strforce(_("Wins")),
                strforce(_("Beats"))
            ])
            for index, result in poll.stv_results['wins_and_beats'].items():
                beats = map(lambda x: indexed_cands[str(x)], result[1])
                writerow([
                    strforce(indexed_cands[index]), result[0],
                    strforce(u",".join(beats))
                ])

            writerow([])
            writerow([])
            writerow([strforce(_("Ballots"))]),
            for ballot in poll.stv_results['ballots']:
                writerow(map(str, ballot))
Example #4
0
def csv_from_preference_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow

        make_csv_intro(writerow, election, lang)
        for poll in polls:
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            writerow([strforce(_("Candidates"))])
            for item in questions[0]['answers']:
                writerow([strforce(item)])


            writerow([])
            writerow([])
            writerow([strforce(_("Candidate")), strforce(_("Wins")),
                      strforce(_("Beats"))])
            for index, result in poll.stv_results['wins_and_beats'].items():
                beats = map(lambda x: indexed_cands[str(x)], result[1])
                writerow([strforce(indexed_cands[index]), result[0], strforce(u",".join(beats))])

            writerow([])
            writerow([])
            writerow([strforce(_("Ballots"))]),
            for ballot in poll.stv_results['ballots']:
                writerow(map(str, ballot))
Example #5
0
def csv_from_unigovgr_results(election, results, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow
        make_csv_intro(writerow, election, lang)


        def get(g, key):
            keys = key.split('.')
            obj = results[g]
            while len(keys):
                obj = obj[keys.pop(0)]
            return obj

        T = partial(get, 'totals')
        A = partial(get, 'group_a')
        B = partial(get, 'group_b')

        def ROW(label, key):
            return [strforce(label), strforce(T(key)), strforce(A(key)), strforce(B(key))]

        writerow([])
        writerow([])
        writerow([])
        writerow([])
        writerow([])
        writerow(['',strforce(_("Total")), strforce(A('name')), strforce(B('name'))])
        writerow(ROW(_("Voters"), 'voters'))
        if T('excluded') > 0:
            writerow(ROW(_("Excluded voters"), 'excluded'))
        writerow([])
        writerow([strforce(_('RESULTS'))])
        writerow(ROW(_('TOTAL VOTES'), 'voted'))
        writerow(ROW(_('VALID VOTES'), 'valid'))
        writerow(ROW(_('INVALID VOTES'), 'invalid'))
        writerow(ROW(_('BLANK VOTES'), 'blank'))

        writerow([])
        writerow([strforce(_('RESULTS'))])
        for question, answers in T('counts').items():
            writerow([])
            writerow([strforce(question)])
            writerow(['',strforce(_("Total rounded")), strforce(_("Total")), strforce(A('name')), strforce(B('name'))])
            for answer in answers:
                key = u'counts.%s.%s' % (question, answer)
                key_round = u'counts_rounded.%s.%s' % (question, answer)
                writerow([
                    strforce(answer),
                    strforce(T(key_round)),
                    strforce(T(key)),
                    strforce(A(key)),
                    strforce(B(key))
                ])

        writerow([])
        writerow([strforce(_('BALLOTS'))])
        writerow([strforce(_('GROUP')), strforce(_('ID')), strforce(_('QUESTION')),\
            strforce(_('CANDIDATE')), strforce(_('VALID/INVALID/BLANK'))])
        counter = 0
        valid = strforce(_('VALID'))
        invalid = strforce(_('INVALID'))
        blank = strforce(_('BLANK'))
        empty = '---'
        for ballot in T('ballots'):
            unigov_group = strforce(ballot['unigov_group'])
            party = empty
            counter += 1
            if not ballot['valid']:
                writerow([unigov_group, counter, empty, empty, invalid])
                continue
            ballot_parties = ballot['parties']
            if not ballot_parties:
                writerow([unigov_group, counter, empty, empty, blank])
            else:
                for party in ballot_parties:
                    if party is None:
                        writerow([unigov_group, counter, empty, empty, empty])
                        continue
                    else:
                        party = strforce(party)

            candidates = ballot['candidates']
            if not candidates:
                writerow([unigov_group, counter, party, empty, valid])
                continue

            for candidate in candidates:
                writerow([unigov_group, counter, party, strforce(": ".join(candidate)), valid])

        try:
            outfile.seek(0)
            return outfile.read()
        except:
            return None
Example #6
0
def csv_from_score_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow
        make_csv_intro(writerow, election, lang)

        for poll in polls:
            score_results = poll.zeus.get_results()
            invalid_count = len([b for b in score_results['ballots']
                                if b['valid'] == False])
            blank_count = len([b for b in score_results['ballots']
                            if not b.get('candidates')])
            ballot_count = len(score_results['ballots'])

            writerow([])
            writerow([])
            writerow([])
            writerow([strforce(poll.name)])
            writerow([])
            writerow([])
            writerow([strforce(_('RESULTS'))])
            writerow([strforce(_('TOTAL VOTES')), strforce(ballot_count)])
            writerow([strforce(_('VALID VOTES')), strforce(ballot_count - invalid_count)])
            writerow([strforce(_('INVALID VOTES')), strforce(invalid_count)])
            writerow([strforce(_('BLANK VOTES')), strforce(blank_count)])

            writerow([])
            writerow([strforce(_('RANKING'))])
            for score, candidate in sorted(score_results['totals']):
                candidate = candidate.replace("{newline}", " ")
                writerow([strforce(score), strforce(candidate)])

            writerow([])
            writerow([strforce(_('SCORES'))])
            pointlist = list(sorted(score_results['points']))
            pointlist.reverse()
            writerow([strforce(_('CANDIDATE')), strforce(_('SCORES:'))] + pointlist)
            for candidate, points in sorted(score_results['detailed'].iteritems()):
                writerow([strforce(candidate), ''] +
                        [strforce(points[p]) for p in pointlist])

            writerow([])
            writerow([strforce(_('BALLOTS'))])
            writerow([strforce(_('ID')), strforce(_('CANDIDATE')),\
                strforce(_('SCORES')), strforce(_('VALID/INVALID/BLANK'))])
            counter = 0
            valid = strforce(_('VALID'))
            invalid = strforce(_('INVALID'))
            blank = strforce(_('BLANK'))
            empty = '---'
            for ballot in score_results['ballots']:
                counter += 1
                if not ballot['valid']:
                    writerow([counter, empty, empty, invalid])
                    continue
                points = sorted(ballot['candidates'].iteritems())
                for candidate, score in points:
                    candidate = candidate.replace("{newline}", " ")
                    writerow([strforce(counter), strforce(candidate),
                            strforce(score), valid])
        try:
            outfile.seek(0)
            return outfile.read()
        except:
            return None
Example #7
0
def csv_from_stv_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow

        make_csv_intro(writerow, election, lang)
        actions_desc = {
            'elect': _('Elect'),
            'eliminate': _('Eliminated'),
            'quota': _('Eliminated due to quota restriction')}
        from stv.parser import STVParser
        for poll in polls:
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            results_winners = poll.stv_results[0]
            results_all = poll.stv_results[1]
            result_steps = poll.stv_results[2]
            stv = STVParser(result_steps)
            rounds = list(stv.rounds())
            writerow([])
            writerow([strforce(_("Candidates"))])
            for item in questions[0]['answers']:
                writerow([strforce(item)])
            writerow([])
            writerow([strforce(_("Elected")), strforce(_("Departments"))])
            for winner_data in results_winners:
                 winner_id = winner_data[0]
                 winner = indexed_cands[str(winner_id)]
                 winner_name, winner_department = winner, ''
                 if ':' in winner:
                    winner_params = winner.split(':')
                    winner_name = winner_params[0]
                    winner_department = winner_params[1]
                 writerow([strforce(winner_name), strforce(winner_department)])
            for num, round in rounds:
                round_name = _('Round ')
                round_name +=str(num)
                writerow([])
                writerow([strforce(round_name)])
                writerow([strforce(_('Candidate')), strforce(_('Votes')),\
                    strforce(_('Draw')), strforce(_('Action'))])
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    writerow([strforce(cand_name),strforce(votes),\
                    strforce(draw), strforce(action)])
Example #8
0
def csv_from_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow
        make_csv_intro(writerow, election, lang)
        for poll in polls:
            party_results = poll.zeus.get_results()
            invalid_count = party_results['invalid_count']
            blank_count = party_results['blank_count']
            ballot_count = party_results['ballot_count']

            writerow([])
            writerow([])
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            writerow([])
            nr_voters = poll.voters.all().count()
            writerow([strforce(_("Voters")), strforce(nr_voters)])
            if poll.voters.all().excluded().count() > 0:
                ex_voters = poll.voters.all().excluded().count()
                writerow([strforce(_("Excluded voters")), strforce(ex_voters)])
            writerow([])
            writerow([strforce(_('RESULTS'))])
            writerow([strforce(_('TOTAL VOTES')), strforce(ballot_count)])
            writerow([strforce(_('VALID VOTES')), strforce(ballot_count - invalid_count)])
            writerow([strforce(_('INVALID VOTES')), strforce(invalid_count)])
            writerow([strforce(_('BLANK VOTES')), strforce(blank_count)])

            writerow([])
            writerow([strforce(_('PARTY RESULTS'))])
            party_counters = party_results['party_counts']
            for count, party in party_results['party_counts']:
                if party is None:
                    continue
                party = party.replace("{newline}", " ")
                writerow([strforce(party), strforce(count)])

            writerow([])
            writerow([strforce(_('CANDIDATE RESULTS'))])
            for count, candidate in party_results['candidate_counts']:
                writerow([strforce(candidate), strforce(count)])

            writerow([])
            writerow([strforce(_('BALLOTS'))])
            writerow([strforce(_('ID')), strforce(_('PARTY')),\
                strforce(_('CANDIDATE')), strforce(_('VALID/INVALID/BLANK'))])
            counter = 0
            valid = strforce(_('VALID'))
            invalid = strforce(_('INVALID'))
            blank = strforce(_('BLANK'))
            empty = '---'
            for ballot in party_results['ballots']:
                party = empty
                counter += 1
                if not ballot['valid']:
                    writerow([counter, empty, empty, invalid])
                    continue
                ballot_parties = ballot['parties']
                if not ballot_parties:
                    writerow([counter, empty, empty, blank])
                else:
                    for party in ballot_parties:
                        if party is None:
                            writerow([counter, empty, empty, empty])
                            continue
                        else:
                            party = strforce(party)

                candidates = ballot['candidates']
                if not candidates:
                    writerow([counter, party, empty, valid])
                    continue

                for candidate in candidates:
                    writerow([counter, party, strforce(": ".join(candidate)), valid])

        try:
            outfile.seek(0)
            return outfile.read()
        except:
            return None