Exemplo n.º 1
0
    def test_stv_landslide(self):

        # Generate data
        input = [{
            "count": 56,
            "ballot": ["c1", "c2", "c3"]
        }, {
            "count": 40,
            "ballot": ["c2", "c3", "c1"]
        }, {
            "count": 20,
            "ballot": ["c3", "c1", "c2"]
        }]
        output = STV(input, required_winners=2).as_dict()

        # Run tests
        self.assertEqual(
            output, {
                'candidates':
                set(['c1', 'c2', 'c3']),
                'quota':
                39,
                'rounds': [{
                    'tallies': {
                        'c3': 20.0,
                        'c2': 40.0,
                        'c1': 56.0
                    },
                    'winners': set(['c2', 'c1'])
                }],
                'winners':
                set(['c2', 'c1'])
            })
Exemplo n.º 2
0
    def test_stv_ian_jacobs_3(self):

        # Generate data
        input = [
            {
                "count": 3,
                "ballot": ["A", "X", "D"]
            },
            {
                "count": 3,
                "ballot": ["B", "X", "D"]
            },
            {
                "count": 2,
                "ballot": ["C", "X"]
            },
            {
                "count": 1,
                "ballot": ["D", "X"]
            },
        ]
        output = STV(input, required_winners=3).as_dict()

        # Run tests
        self.assertEqual(output["winners"], set(["A", "B", "C"]))
Exemplo n.º 3
0
    def stv_results(self, winners=None):
        # FIXME: Variable names here may be somewhat confusing.
        #     - winners: The count of required winners.
        #     - winnerset: The set of winners returned.
        if winners is None:
            winners = 1

        winnerset = []

        mid_result = STV(list(self.hashes_with_counts(
            self.ballots_as_lists())),
                         required_winners=winners).as_dict()
        winners_found = 0
        for mid_round in mid_result['rounds']:
            if not 'winners' in mid_round:
                continue

            found_this_time = len(mid_round['winners'])
            if winners_found + found_this_time > winners:
                winnerset.extend(
                    random.sample(mid_round['winners'],
                                  winners - winners_found))
            else:
                winnerset.extend(mid_round['winners'])

            winners_found += found_this_time

        if len(winnerset) < winners:
            return mid_result['winners']

        return winnerset
Exemplo n.º 4
0
    def test_stv_ian_jacobs_2(self):

        # Generate data
        input = [{
            "count": 1,
            "ballot": ["A", "B", "C"]
        }, {
            "count": 1,
            "ballot": ["A", "D", "B", "G"]
        }, {
            "count": 1,
            "ballot": ["D", "A", "C", "E", "B", "F"]
        }, {
            "count": 1,
            "ballot": ["E", "A", "C", "F", "B", "D"]
        }, {
            "count": 1,
            "ballot": ["F", "C", "B"]
        }, {
            "count": 1,
            "ballot": ["C", "F", "A", "G"]
        }, {
            "count": 1,
            "ballot": ["A", "E", "B", "D", "C", "F"]
        }, {
            "count": 1,
            "ballot": ["F", "E", "D", "A", "C", "B", "G"]
        }, {
            "count": 1,
            "ballot": ["C", "F", "D"]
        }, {
            "count": 1,
            "ballot": ["C", "A", "E", "F", "D", "B", "G"]
        }, {
            "count": 1,
            "ballot": ["F", "B", "A", "C", "E", "D"]
        }, {
            "count": 1,
            "ballot": ["D", "A", "B", "F", "E", "C", "G"]
        }, {
            "count": 1,
            "ballot": ["D", "B", "C", "F", "A", "E", "G"]
        }, {
            "count": 1,
            "ballot": ["A", "F", "C", "E", "B", "G"]
        }, {
            "count": 1,
            "ballot": ["F", "A", "B"]
        }]
        output = STV(input, required_winners=4).as_dict()

        # Run tests
        self.assertEqual(output["winners"], set(['A', 'C', 'D', 'F']))
Exemplo n.º 5
0
    def test_stv_single_ballot(self):

        # Generate data
        input = [
            {
                "count": 1,
                "ballot": ["c1", "c2", "c3", "c4"]
            },
        ]
        output = STV(input, required_winners=3).as_dict()

        # Run tests
        self.assertEqual(
            output, {
                'candidates':
                set(['c1', 'c2', 'c3', 'c4']),
                'quota':
                1,
                'rounds': [
                    {
                        'tallies': {
                            'c1': 1.0,
                            'c2': 0,
                            'c3': 0,
                            'c4': 0
                        },
                        'winners': set(['c1'])
                    },
                    {
                        'note': 'reset',
                        'tallies': {
                            'c2': 1.0,
                            'c3': 0,
                            'c4': 0
                        },
                        'winners': set(['c2'])
                    },
                    {
                        'note': 'reset',
                        'tallies': {
                            'c3': 1.0,
                            'c4': 0
                        },
                        'winners': set(['c3'])
                    },
                ],
                'winners':
                set(['c1', 'c2', 'c3'])
            })
	def do_POST(self):
		try:
			# Parse the incoming data
			request_raw = self.rfile.read(int(self.headers["content-length"]))
			request_raw = re.sub("\n", "", request_raw)
			request = json.loads(request_raw)
			
			# Send the data to the requested voting system
			if request["voting_system"] == "plurality":
				system = Plurality(request["ballots"])
			elif request["voting_system"] == "plurality_at_large":
				system = PluralityAtLarge(request["ballots"], required_winners = request["winners"])
			elif request["voting_system"] == "irv":
				system = IRV(request["ballots"])
			elif request["voting_system"] == "stv":
				system = STV(request["ballots"], required_winners = request["winners"])
			elif request["voting_system"] == "schulze_method":
				system = SchulzeMethod(request["ballots"], ballot_notation = request["notation"])
			elif request["voting_system"] == "schulze_stv":
				system = SchulzeSTV(request["ballots"], required_winners = request["winners"], ballot_notation = request["notation"])
			elif request["voting_system"] == "schulze_pr":
				system = SchulzePR(request["ballots"], winner_threshold = request["winners"], ballot_notation = request["notation"])
			else:
				raise Exception("No voting system specified")
			response = system.as_dict()
			
			# Ensure a response came back from the voting system
			if response == None:
				raise
		
		except:
			fp = StringIO.StringIO()
			traceback.print_exc(10,fp)
			response = fp.getvalue()
			self.send_response(500)
		
		else:
			self.send_response(200)
		
		finally:
			response = json.dumps(self.__simplify_object__(response))
			self.send_header("Content-type", "application/json")
			self.send_header("Content-length", str(len(response)))
			self.end_headers()
			self.wfile.write(response)
Exemplo n.º 7
0
    def test_stv_everyone_wins(self):

        # Generate data
        input = [{
            "count": 56,
            "ballot": ["c1", "c2", "c3"]
        }, {
            "count": 40,
            "ballot": ["c2", "c3", "c1"]
        }, {
            "count": 20,
            "ballot": ["c3", "c1", "c2"]
        }]
        output = STV(input, required_winners=3).as_dict()

        # Run tests
        self.assertEqual(
            output, {
                'candidates': set(['c1', 'c2', 'c3']),
                'quota': 30,
                'rounds': [],
                'remaining_candidates': set(['c1', 'c2', 'c3']),
                'winners': set(['c1', 'c2', 'c3'])
            })
Exemplo n.º 8
0
from pyvotecore.stv import STV
import json

f = open("count.json", "r")
input_json = json.load(f)
f.close()

input_list = []

for each in input_json:
    dict_here = {"count": input_json[each], "ballot": json.loads(each)}
    input_list.append(dict_here)

output = STV(input_list, required_winners=15).as_dict()
print(output)


class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj)


with open('stv.txt', 'w') as f:
    f.write(str(output))

with open('stv.json', 'w') as f:
    json.dump(output, f, cls=SetEncoder)
Exemplo n.º 9
0
    list(map(parse, s.split('\t'))) for s in ballots_data.split('\n') if s
]
print(ballots_marks)

ballots_marks_temp = [[3, 1, 2], [3, 1, 2], [3, 2, 1]]


def to_ballot(array):
    a = [x[0] for x in sorted(zip(candidates, array), key=lambda x: -x[1])]
    return {"ballot": [x for x in a]}


def to_ballot_list(array):
    a = [x[0] for x in sorted(zip(candidates, array), key=lambda x: -x[1])]
    return {"ballot": [[x] for x in a]}


from pyvotecore.schulze_method import SchulzeMethod
from pyvotecore.schulze_stv import SchulzeSTV
from pyvotecore.condorcet import CondorcetHelper
#a = SchulzeMethod(list(map(to_ballot_list, ballots_marks)), ballot_notation = CondorcetHelper.BALLOT_NOTATION_GROUPING).as_dict()
#print(a)
#b = STV(list(map(to_ballot, ballots_marks)), required_winners=2).as_dict()
#print(b)
c = SchulzeSTV(list(map(to_ballot_list, ballots_marks)),
               required_winners=6,
               ballot_notation=SchulzeSTV.BALLOT_NOTATION_GROUPING).as_dict()
print(c)
d = STV(list(map(to_ballot, ballots_marks)), required_winners=6).as_dict()
print(d)
Exemplo n.º 10
0
    def test_stv_wiki_example(self):

        # Generate data
        input = [{
            "count": 4,
            "ballot": ["orange"]
        }, {
            "count": 2,
            "ballot": ["pear", "orange"]
        }, {
            "count": 8,
            "ballot": ["chocolate", "strawberry"]
        }, {
            "count": 4,
            "ballot": ["chocolate", "sweets"]
        }, {
            "count": 1,
            "ballot": ["strawberry"]
        }, {
            "count": 1,
            "ballot": ["sweets"]
        }]
        output = STV(input, required_winners=3).as_dict()

        # Run tests
        self.assertEqual(
            output, {
                'candidates':
                set(['orange', 'pear', 'chocolate', 'strawberry', 'sweets']),
                'quota':
                6,
                'rounds': [{
                    'tallies': {
                        'orange': 4.0,
                        'strawberry': 1.0,
                        'pear': 2.0,
                        'sweets': 1.0,
                        'chocolate': 12.0
                    },
                    'winners': set(['chocolate'])
                }, {
                    'tallies': {
                        'orange': 4.0,
                        'strawberry': 5.0,
                        'pear': 2.0,
                        'sweets': 3.0
                    },
                    'loser': 'pear'
                }, {
                    'tallies': {
                        'orange': 6.0,
                        'strawberry': 5.0,
                        'sweets': 3.0
                    },
                    'winners': set(['orange'])
                }, {
                    'tallies': {
                        'strawberry': 5.0,
                        'sweets': 3.0
                    },
                    'loser': 'sweets'
                }],
                'remaining_candidates':
                set(['strawberry']),
                'winners':
                set(['orange', 'strawberry', 'chocolate'])
            })
Exemplo n.º 11
0
    def test_stv_ian_jacobs(self):

        # Generate data
        input = [
            {
                "count": 1,
                "ballot": ["AB", "EF", "BC"]
            },
            {
                "count": 1,
                "ballot": ["AB", "KL", "EF", "HI"]
            },
            {
                "count": 1,
                "ballot": ["EF", "AB", "QR"]
            },
            {
                "count": 1,
                "ballot": ["KL", "AB", "BC", "ST", "EF", "QR"]
            },
            {
                "count": 1,
                "ballot": ["ST", "AB", "BC", "QR", "EF", "KL"]
            },
            {
                "count": 1,
                "ballot": ["QR", "BC", "EF"]
            },
            {
                "count": 1,
                "ballot": ["BC", "QR", "AB", "HI"]
            },
            {
                "count": 1,
                "ballot": ["BC", "AB", "ST", "QR", "KL", "EF", "HI"]
            },
            {
                "count": 1,
                "ballot": ["QR", "EF", "AB", "BC", "ST", "KL"]
            },
            {
                "count": 1,
                "ballot": ["KL", "AB", "EF", "QR", "ST", "BC", "HI"]
            },
            {
                "count": 1,
                "ballot": ["AB", "ST", "EF", "KL", "BC", "QR"]
            },
            {
                "count": 1,
                "ballot": ["QR", "ST", "KL", "AB", "BC", "EF", "HI"]
            },
            {
                "count": 1,
                "ballot": ["BC", "QR", "KL"]
            },
        ]
        output = STV(input, required_winners=3).as_dict()

        # Run tests
        self.assertEqual(output["winners"], set(["AB", "BC", "QR"]))
Exemplo n.º 12
0
 def stv_results(self, winners=None):
     if winners is None:
         winners = 1
     return list(
         STV(list(self.hashes_with_counts(self.ballots_as_lists())),
             required_winners=winners).as_dict()['winners'])