Created
June 12, 2020 21:42
-
-
Save carlosgmartin/cd268fdbe5eaa906b68d36b64726c3c2 to your computer and use it in GitHub Desktop.
Solving batches of two-player zero-sum normal-form games
This file contains 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
import numpy as np | |
import gurobipy | |
import cvxopt | |
from multiprocessing import Pool | |
from timeit import default_timer as timer | |
gurobipy.setParam('OutputFlag', 0) | |
def max_min_gurobi(game): | |
model = gurobipy.Model() | |
v = model.addMVar(1) | |
x = model.addMVar(game.shape[0]) | |
model.setObjective(v.sum(), gurobipy.GRB.MAXIMIZE) | |
model.addConstr(x.sum() == 1) | |
model.addConstr(x >= 0) | |
model.addConstrs(( | |
v <= game[:, i] @ x | |
for i in range(game.shape[1]) | |
)) | |
model.optimize() | |
return model.objVal | |
cvxopt.solvers.options['glpk'] = {'msg_lev' : 'GLP_MSG_OFF'} | |
def max_min_cvxopt(game): | |
return -cvxopt.solvers.lp( | |
solver='glpk', | |
c=cvxopt.matrix(-np.concatenate((np.ones(1), np.zeros(game.shape[0])))), | |
G=cvxopt.matrix(np.concatenate(( | |
np.concatenate(( | |
np.eye(1)[:, :, None].repeat(game.shape[1], 2), | |
-game[None], | |
), 1).swapaxes(1, 2).reshape(game.shape[1], 1 + game.shape[0]), | |
-np.eye(1 + game.shape[0])[1:] | |
), 0)), | |
h=cvxopt.matrix(np.zeros(game.shape[1] + game.shape[0])), | |
A=cvxopt.matrix(np.concatenate((np.zeros(1), np.ones(game.shape[0])))[None]), | |
b=cvxopt.matrix(np.ones(1)) | |
)['primal objective'] | |
pool = Pool() | |
def max_min(game_batch, method): | |
return np.array(pool.map(method, game_batch)) | |
rng = np.random.default_rng() | |
while True: | |
game_batch = rng.uniform(size=(20, 30, 40)) | |
start = timer() | |
v_gurobi = max_min(game_batch, max_min_gurobi) | |
t_gurobi = timer() - start | |
start = timer() | |
v_cvxopt = max_min(game_batch, max_min_cvxopt) | |
t_cvxopt = timer() - start | |
assert np.allclose(v_gurobi, v_cvxopt) | |
print('gurobi {}\ncvxopt {}\n'.format(t_gurobi, t_cvxopt)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment