Created
August 29, 2020 23:23
-
-
Save DominikPeters/48f8605ed6c1f8ffae291f511905304c to your computer and use it in GitHub Desktop.
Calculate Kemeny's rule using gurobipy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from gurobipy import * | |
import itertools | |
def better(vote, a, b): | |
return vote.index(a) < vote.index(b) | |
def kemeny(profile): | |
# a profile is a list of rankings, e.g. [(0,1,2),(1,2,0),(1,2,0)] | |
C = profile[0] | |
w = {} | |
for a, b in itertools.permutations(C, 2): | |
w[a,b] = 0 | |
for vote in profile: | |
if better(vote, a, b): | |
w[a,b] += 1 | |
else: | |
w[a,b] -= 1 | |
m = Model() | |
m.params.OutputFlag = 0 | |
x = {} | |
for a, b in itertools.combinations(C, 2): | |
x[a,b] = m.addVar(vtype=GRB.BINARY) | |
x[b,a] = m.addVar(vtype=GRB.BINARY) | |
m.addConstr(x[a,b] + x[b,a] == 1) | |
m.addConstrs(x[a,b] + x[b,c] + x[c,a] <= 2 for a,b,c in itertools.permutations(C,3)) | |
m.setObjective(quicksum(x[a,b] * w[a,b] for a, b in itertools.permutations(C, 2)), GRB.MAXIMIZE) | |
m.optimize() | |
return tuple(sorted(C, key=lambda a : -sum(x[a,b].x for b in C if b != a))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment