Created
September 26, 2014 11:34
-
-
Save drvinceknight/7a72d952b91041905d8a to your computer and use it in GitHub Desktop.
A Sage interact to play with 2 by 2 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
def Pure_Nash_Check(A,B,i,j): | |
if i==0: | |
if j==0: | |
if A[0,0]<A[1,0] or B[0,0]<B[0,1]: | |
return False | |
if j==1: | |
if A[0,1]<A[1,1] or B[0,1]<B[0,0]: | |
return False | |
if i==1: | |
if j==0: | |
if A[1,0]<A[0,0] or B[1,0]<B[1,1]: | |
return False | |
if j==1: | |
if A[1,1]<A[0,1] or B[1,1]<B[1,0]: | |
return False | |
return True | |
def Nash(A,B): | |
r=[] | |
#Identify all pure equilibria | |
for i in range(2): | |
for j in range(2): | |
if Pure_Nash_Check(A,B,i,j): | |
if i==0: | |
p1=[1,0] | |
else: | |
p1=[0,1] | |
if j==0: | |
p2=[1,0] | |
else: | |
p2=[0,1] | |
r.append([p1,p2]) | |
#If not all equilibria found identify mixed equilibria (since in a 2 by 2 game only 1 mixed equilibria possible) | |
if len(r)%2==0: | |
var("p,q") | |
p=solve(B[0,0]*x+B[1,0]*(1-x)==B[0,1]*x+B[1,1]*(1-x),x,solution_dict=True)[0][x] | |
q=solve(A[0,0]*x+A[0,1]*(1-x)==A[1,0]*x+A[1,1]*(1-x),x,solution_dict=True)[0][x] | |
p1=[p,1-p] | |
p2=[q,1-q] | |
r.append([p1,p2]) | |
return r | |
@interact | |
def _(A=matrix(RDF,2,2,[4,1,1,2]),p=(slider(0,1,.05)),B=matrix(RDF,2,2,[2,1,1,4]),q=(slider(0,1,.05))): | |
show("Utilities:") | |
p1_util= lambda x,y: x*y*A[0,0]+x*(1-y)*A[0,1]+(1-x)*y*A[1,0]+(1-x)*(1-y)*A[1,1] | |
p2_util= lambda x,y: x*y*B[0,0]+x*(1-y)*B[0,1]+(1-x)*y*B[1,0]+(1-x)*(1-y)*B[1,1] | |
p_static=copy(p) | |
q_static=copy(q) | |
p=plot(p1_util(x,q),(x,0,1),legend_label='Player 1',thickness=3) | |
if p1_util(0,q)==p2_util(p_static,0) and p1_util(1,q)==p2_util(p_static,1): | |
p+=plot(p2_util(p_static,x),(x,0,1),legend_label='Player 2',color='red',thickness=2) | |
else: | |
p+=plot(p2_util(p_static,x),(x,0,1),legend_label='Player 2',color='red',thickness=3) | |
p_max=max(flatten(list([list(a) for a in A]))) | |
p_max=max(p_max,max(flatten(list([list(b) for b in B])))) | |
p.ymax(p_max) | |
p_min=min(flatten(list([list(a) for a in A]))) | |
p_min=min(p_min,min(flatten(list([list(b) for b in B])))) | |
p.ymin(p_min) | |
p.axes_labels(['First strategy','Utility']) | |
show(p) | |
r=Nash(A,B) | |
l=len(r) | |
if l==1: | |
show("Single equilibria:") | |
show(r[0]) | |
return | |
for e in r: | |
if l!=1: | |
show("Equilibria number %s:"%(r.index(e)+1)) | |
show(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment