Skip to content

Instantly share code, notes, and snippets.

@DominikPeters
Created August 29, 2020 23:23
Show Gist options
  • Save DominikPeters/48f8605ed6c1f8ffae291f511905304c to your computer and use it in GitHub Desktop.
Save DominikPeters/48f8605ed6c1f8ffae291f511905304c to your computer and use it in GitHub Desktop.
Calculate Kemeny's rule using gurobipy
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