import numpy as np
import matplotlib.pyplot as plt 
from matplotlib import rcParams

# Definition der Funktion g
def g(x,a,b,c,d):
    g = ((a-c)*(x-x*x) + (b-d)*(1-2*x+x*x))*x
    return g

# Loesen der DGL
def solve_dgl(numpoints,tend,x0,a,b,c,d):
    sol = np.empty([numpoints,2])
    t = np.linspace(0,tend,numpoints)
    dt = t[1]-t[0]
    sol[0][0] = t[0]
    sol[0][1] = x0
    for i in range(1,numpoints):
        sol[i][0] = t[i]
        dx = g(sol[i-1,1],a,b,c,d)*dt
        sol[i][1] = sol[i-1,1] + dx
    return sol

# Groessenfestlegung der Labels usw. im Bild
rcParams.update({
    'text.usetex'       : True,
    'axes.titlesize' : 22,
    'axes.labelsize' : 20,  
    'xtick.labelsize' : 20 ,
    'ytick.labelsize' : 20 
})

#Festlegung der Auszahlungsmatrix des symmetrischen (2x2)-Spiels
# Dominant Game
#a = -7
#b = -1
#c = -9
#d = -3
#tend=4
# Koordinantionsspiel
a = 2
b = 4
c = 0
d = 5
tend = 6
# Anti-Koordinantionsspiel
#a = -10
#b = 2
#c = 0
#d = 1
#tend = 3

#Weitere Festlegungen
numpoints = 500
curvethick = 1.5

# Definition der Kurvenfarbe in Abhaengigkeit von der Spielklasse
# Dominant Games
if a > c and b > d:
    cmap = plt.cm.Greys
    texttitle = r'$\rm Dominantes\, Spiel $'
if a < c and b < d:
    cmap = plt.cm.Greys
    texttitle = r'$\rm Dominantes\, Spiel $'
# Koordinantionsspiele
if a > c and b < d:
    cmap = plt.cm.Blues
    texttitle = r'$\rm Koordinationsspiel $'
# Anti-Koordinantionsspiele
if a < c and b > d:
    cmap = plt.cm.Oranges
    texttitle = r'$\rm Anti-Koordinationsspiel $'

# Mehrere Anfangswerte der Population
num_x0 = 30
x0 = np.linspace(0,1,num_x0)
line_colors = cmap(np.linspace(0,1,num_x0+10))

# Loesung der DGL und plotten des Bildes
for j in range(num_x0):
    Loes = solve_dgl(numpoints,tend,x0[j],a,b,c,d)
    plt.plot(Loes[:,0],Loes[:,1],c=line_colors[j+5], linewidth=curvethick, linestyle='-')

# Plotten der Spielmatrix in das Bild
textstr1 = r'$\hat{\bf {\cal \$}} = \left( \begin{array}[c]{cc} a & b \\ \ c & d \end{array} \right)\\a='+str(a)+', b='+str(b)+'$'
textstr2 = r'$\\c='+str(c)+', d='+str(d)+'$'
props = dict(boxstyle='round', facecolor='white', alpha=0.92)
plt.text(tend-tend/50.0, 0.98, textstr1+textstr2, fontsize=16, verticalalignment='top', horizontalalignment='right', bbox=props)

# Achsenbeschriftungen usw.
plt.ylim(0,1)
plt.yticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1],["$0$","","$0.2$","","$0.4$","","$0.6$","","$0.8$","","$1$"])
plt.ylabel(r"$\rm x(t)$")
plt.xlabel(r"$\rm t$")
plt.title(texttitle)


#Speichern der Bilder als (.png , benoetigt dvipng unter Linux)- und .pdf-Datei
saveFig="./evol.png"
plt.savefig(saveFig, dpi=100,bbox_inches="tight",pad_inches=0.05,format="png")
saveFig = "./evol.pdf"
plt.savefig(saveFig,bbox_inches="tight",pad_inches=0.05,format="pdf")
plt.show()
