示例#1
0
    def compute_results(self):
        cands_data = self.poll.questions_data[0]['answers']
        cands_count = len(cands_data)
        constituencies = {}
        count_id = 0

        for item in cands_data:
            cand_and_dep = item.split(':')
            constituencies[str(count_id)] = cand_and_dep[1]
            count_id += 1

        seats = self.poll.eligibles_count
        droop = self.poll.stv_droop
        rnd_gen = None  # TODO: should be generated and stored on poll freeze
        if self.poll.has_department_limit:
            quota_limit = self.poll.department_limit
        else:
            quota_limit = 0
        ballots_data = self.poll.result[0]
        ballots = []
        for ballot in ballots_data:
            if not ballot:
                continue
            ballot = to_absolute_answers(
                gamma_decode(ballot, cands_count, cands_count), cands_count)
            ballot = [str(i) for i in ballot]
            ballots.append(Ballot(ballot))

        stv_stream = StringIO.StringIO()
        stv_logger = logging.Logger(self.poll.uuid)
        handler = logging.StreamHandler(stv_stream)
        stv_logger.addHandler(handler)
        stv_logger.setLevel(logging.DEBUG)
        self.poll.logger.info(
            "Count STV results [seats:{} droop:{} quota_limit:{}]".format(
                seats, droop, quota_limit))
        results = count_stv(ballots,
                            seats,
                            droop,
                            constituencies,
                            quota_limit,
                            rnd_gen,
                            logger=stv_logger)
        results = list(results[0:2])
        handler.close()
        stv_stream.seek(0)
        results.append(stv_stream.read())
        stv_stream.close()
        self.poll.stv_results = json.dumps(results)
        self.poll.save()

        # build docs
        self.generate_json_file()
        for lang in settings.LANGUAGES:
            #self.generate_csv_file(lang)
            self.generate_result_docs(lang)
            self.generate_csv_file(lang)
示例#2
0
    def compute_results(self):
        cands_data = self.poll.questions_data[0]['answers']
        cands_count =  len(cands_data)
        constituencies = {}
        count_id = 0

        for item in cands_data:
            cand_and_dep = item.split(':')
            constituencies[str(count_id)] = cand_and_dep[1]
            count_id += 1

        seats = self.poll.eligibles_count
        droop = False
        rnd_gen = None # TODO: should be generated and stored on poll freeze
        if self.poll.has_department_limit:
            quota_limit = self.poll.department_limit
        else:
            quota_limit = 0
        ballots_data = self.poll.result[0]
        ballots = []
        for ballot in ballots_data:
            if not ballot:
                continue
            ballot = to_absolute_answers(gamma_decode(ballot, cands_count,cands_count),
                                         cands_count)
            ballot = [str(i) for i in ballot]
            ballots.append(Ballot(ballot))

        stv_stream = StringIO.StringIO()
        stv_logger = logging.Logger(self.poll.uuid)
        handler = logging.StreamHandler(stv_stream)
        stv_logger.addHandler(handler)
        stv_logger.setLevel(logging.DEBUG)
        results = count_stv(ballots, seats, droop, constituencies, quota_limit,
                            rnd_gen, logger=stv_logger)
        results = list(results[0:2])
        handler.close()
        stv_stream.seek(0)
        results.append(stv_stream.read())
        stv_stream.close()
        self.poll.stv_results = json.dumps(results)
        self.poll.save()

        # build docs
        self.generate_json_file()
        for lang in settings.LANGUAGES: 
            #self.generate_csv_file(lang)
            self.generate_result_docs(lang)
            self.generate_csv_file(lang)
示例#3
0
def stv_count_and_report(uuid, el_data, base_path="/tmp/"):
    eligibles = el_data['numOfEligibles']
    elected_limit = el_data['electedLimit']
    ballots = el_data['ballots']
    input_ballots = []
    elName = el_data.get("elName")
    pollName = el_data.get("pollName", elName)
    institution = el_data.get("institution", "")
    voting_starts = el_data.get("votingStarts", datetime.now())
    voting_ends = el_data.get("votingEnds", datetime.now())
    if isinstance(voting_starts, str):
        voting_starts = datetime.strptime(voting_starts, "%d/%m/%Y %H:%M")
    if isinstance(voting_ends, str):
        voting_ends = datetime.strptime(voting_ends, "%d/%m/%Y %H:%M")

    constituencies = {}
    schools = el_data['schools']
    answers = {}
    answers_list = []

    for item in schools:
        school_name = item['Name']
        for candidate in item['candidates']:
            candId = "{} {} {}:{}".format(candidate['firstName'],
                                          candidate['lastName'],
                                          candidate['fatherName'], school_name)
            answers[str(candidate['candidateTmpId'])] = candId
            answers_list.append(candId)
            constituencies[str(len(answers_list) - 1)] = school_name

    for ballot in ballots:
        orderedCandidateList = []
        for rank in range(1, len(ballot['votes']) + 1):
            for vote in ballot['votes']:
                if vote['rank'] == rank:
                    candId = vote['candidateTmpId']
                    candName = answers[str(candId)]
                    index = str(answers_list.index(candName))
                    orderedCandidateList.append(index)
        input_ballots.append(Ballot(orderedCandidateList))

    stv_stream = io.StringIO()
    stv_logger = logging.Logger("stv-poll")
    handler = logging.StreamHandler(stv_stream)
    stv_logger.addHandler(handler)
    stv_logger.setLevel(logging.DEBUG)

    count_results = count_stv(
        input_ballots,
        eligibles,
        droop=True,
        constituencies=constituencies,
        quota_limit=elected_limit if elected_limit else 0,
        rnd_gen=None,
        logger=stv_logger)

    results = list(count_results[0:2])
    voters = list(range(len(ballots)))

    questions = [{
        'tally_type': 'stv',
        'choice_type': 'stv',
        'question': 'Questions choices',
        'answers': answers_list,
        'answer_urls': [None, None],
        'result_type': 'absolute'
    }]

    handler.close()
    stv_stream.seek(0)
    results.append(stv_stream.read())

    poll_name, poll_results, questions, poll_voters = \
        pollName, results, questions, voters

    class Voters(list):
        def count(self):
            return len(self)

        def excluded(self):
            return Voters()

    filename = os.path.join(base_path, "stv-results-{}.pdf".format(uuid))
    poll_voters = Voters(poll_voters)
    data = [[poll_name, poll_results, questions, poll_voters]]
    build_stv_doc(elName,
                  pollName,
                  institution,
                  voting_starts,
                  voting_ends,
                  None,
                  data,
                  'el',
                  filename=filename)
    return [('pdf', filename)]
示例#4
0
def stv_count_and_report(uuid, el_data, base_path="/tmp/"):
    eligibles = el_data['numOfEligibles']
    elected_limit = el_data['electedLimit']
    ballots = el_data['ballots']
    input_ballots = []
    elName = el_data.get("elName")
    pollName = el_data.get("pollName", elName)
    institution = el_data.get("institution", "")
    voting_starts = el_data.get("votingStarts", datetime.now())
    voting_ends = el_data.get("votingEnds", datetime.now())
    if isinstance(voting_starts, basestring):
        voting_starts = datetime.strptime(voting_starts, "%d/%m/%Y %H:%M")
    if isinstance(voting_ends, basestring):
        voting_ends = datetime.strptime(voting_ends, "%d/%m/%Y %H:%M")


    constituencies = {}
    schools = el_data['schools']
    answers = {}
    answers_list = []

    for item in schools:
        school_name = item['Name']
        for candidate in item['candidates']:
            candId = u"{} {} {}:{}".format(candidate['firstName'],
                                            candidate['lastName'],
                                            candidate['fatherName'],
                                            school_name)
            answers[str(candidate['candidateTmpId'])] = candId
            answers_list.append(candId)
            constituencies[str(len(answers_list)-1)] = school_name

    for ballot in ballots:
        orderedCandidateList = []
        for rank in range(1, len(ballot['votes'])+1):
            for vote in ballot['votes']:
                if vote['rank'] == rank:
                    candId = vote['candidateTmpId']
                    candName = answers[str(candId)]
                    index = str(answers_list.index(candName))
                    orderedCandidateList.append(index)
        input_ballots.append(Ballot(orderedCandidateList))

    stv_stream = StringIO.StringIO()
    stv_logger = logging.Logger("stv-poll")
    handler = logging.StreamHandler(stv_stream)
    stv_logger.addHandler(handler)
    stv_logger.setLevel(logging.DEBUG)

    count_results = count_stv(input_ballots, eligibles,
                                droop=False,
                                constituencies=constituencies,
                                quota_limit=elected_limit if elected_limit else 0,
                                rnd_gen=None, logger=stv_logger)

    results = list(count_results[0:2])
    voters = range(len(ballots))

    questions = [{u'tally_type': u'stv', u'choice_type': u'stv',
                    u'question': u'Questions choices', u'answers':
                    answers_list, u'answer_urls': [None, None],
                    u'result_type': u'absolute'}]

    handler.close()
    stv_stream.seek(0)
    results.append(stv_stream.read())


    poll_name, poll_results, questions, poll_voters = \
        pollName, results, questions, voters

    class Voters(list):
        def count(self):
            return len(self)

        def excluded(self):
            return Voters()

    filename = os.path.join(base_path, "stv-results-{}.pdf".format(uuid))
    poll_voters = Voters(poll_voters)
    data = [[poll_name, poll_results, questions, poll_voters]]
    build_stv_doc(elName, pollName, institution, voting_starts,
                    voting_ends, None, data, 'el',
                    filename=filename)
    return [('pdf', filename)]
示例#5
0
文件: check-stv.py 项目: grnet/zeus
                if vote['rank'] == rank:
                    orderedCandidateList.append(str(vote['candidateTmpId']))
        input_ballots.append(Ballot(orderedCandidateList))

    constituencies = {}
    schools = el_data['schools']
    for item in schools:
        school_name = item['Name']
        for candidate in item['candidates']:
            constituencies[str(candidate['candidateTmpId'])] = school_name
    #third item of count_result containes 'votes'
    draws = [str(c) for c in el_data['draws']]
    rnd_gen = draws if draws else None
    count_results = count_stv(input_ballots, eligibles,
                              droop=False,
                              constituencies=constituencies,
                              quota_limit=2 if hasLimit else 0,
                              rnd_gen=rnd_gen)

    
    #-------------------------------------------------------
    
    #take correct local_results format str8 from stv.py
    local_results = [] 
    for item in count_results[0]:
        for candidate in count_results[2]:
            if item[0] == candidate[0]:
                listed_item = list(item)
                temp_list = []
                temp_list.append(listed_item[0])
                temp_list.append(listed_item[1])