This repository has been archived on 2021-05-25. You can view files and clone it, but cannot push or open issues or pull requests.
pyRCV2/pyRCV2/blt.py

71 lines
2.3 KiB
Python
Raw Normal View History

2020-10-17 18:40:18 +11:00
# pyRCV2: Preferential vote counting
# Copyright © 2020 Lee Yingtong Li (RunasSudo)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
2020-10-17 22:20:13 +11:00
from pyRCV2.model import Ballot, Candidate, Election
from pyRCV2.numbers import Num
2020-10-17 18:40:18 +11:00
class BLTException(Exception):
pass
def readBLT(data):
lines = data.split('\n')
election = Election()
# Read first line
2020-10-17 23:03:32 +11:00
num_candidates = int(lines[0].strip().split(' ')[0])
election.seats = int(lines[0].strip().split(' ')[1])
2020-10-17 18:40:18 +11:00
# Read withdrawn candidates
withdrawn = []
i = 1
2020-10-17 23:03:32 +11:00
if lines[i].strip().startswith('-'):
withdrawn.extend([int(x[1:]) - 1 for x in lines[i].strip().split(' ')])
2020-10-17 18:40:18 +11:00
i += 1
# Read ballots
ballot_data = []
for j in range(i, len(lines)):
2020-10-17 23:03:32 +11:00
if lines[j].strip() == '0': # End of ballots
2020-10-17 18:40:18 +11:00
break
2020-10-17 23:03:32 +11:00
bits = lines[j].strip().split(' ')
2020-10-17 18:40:18 +11:00
preferences = [int(x) - 1 for x in bits[1:] if x != '0']
ballot_data.append((bits[0], preferences))
# Read candidates
for k in range(j + 1, j + 1 + num_candidates):
2020-10-17 23:03:32 +11:00
election.candidates.append(Candidate(lines[k].strip()[1:-1]))
2020-10-17 18:40:18 +11:00
# Read name
if j + 1 + num_candidates < len(lines):
2020-10-17 23:03:32 +11:00
election.name = lines[j + 1 + num_candidates].strip()[1:-1]
2020-10-17 18:40:18 +11:00
# Any additional data?
2020-10-17 23:03:32 +11:00
if len(lines) > j + 2 + num_candidates and len(lines[j + 2 + num_candidates].strip()) > 0:
2020-10-17 18:40:18 +11:00
raise BLTException('Unexpected data at end of BLT file')
if len(lines) > j + 3 + num_candidates:
raise BLTException('Unexpected data at end of BLT file')
# Process ballots
for ballot in ballot_data:
preferences = [election.candidates[x] for x in ballot[1]]
election.ballots.append(Ballot(Num(ballot[0]), preferences))
# Process withdrawn candidates
election.withdrawn = [election.candidates[x] for x in withdrawn]
return election