Example #1
0
def plot_time(iterations):
    iteration = []
    time = []
    timer = Timer()
    mean_time = 0
    for i in range(iterations):
        individuals = 10
        first_operation = Operator(lambda x, y: x + y, '+')
        second_operation = Operator(lambda x, y: x * y, '*')
        operations = [first_operation, second_operation]
        values = [25, 7, 8, 100, 4, 2]
        constants = []
        for value in values:
            constants.append(Constant(value))
        depth = 3
        goal = 459
        timer.start()
        build_programs(individuals, operations, constants, depth, goal, 1000)
        value = timer.stop()
        time.append(value)
        mean_time += value
        iteration.append(i + 1)
    mean_time = mean_time / iterations
    plt.figure()
    plt.title("Tiempo Tomado en 1000 Generaciones", fontsize=20)
    plt.xlabel('Iteración')
    plt.ylabel('Tiempo (segundos)')
    plt.scatter(iteration, time, color='blue')
    plt.axhline(y=mean_time, color='r', linestyle='-')
    plt.show()
Example #2
0
def fitness_vs_population():
    x = []
    y = []
    population = numpy.arange(10, 1010, 10)
    for pop in population:
        individuals = 10
        first_operation = Operator(lambda x, y: x + y, '+')
        second_operation = Operator(lambda x, y: x * y, '*')
        operations = [first_operation, second_operation]
        values = [25, 7, 8, 100, 4, 2]
        constants = []
        for value in values:
            constants.append(Constant(value))
        depth = 3
        goal = 459
        program = Number(individuals, operations, constants, depth, goal)
        program.run(100)
        x.append(pop)
        y.append(program.get_fitness(program.best_individual))
    plt.figure()
    plt.title("Mejor fitness según población inicial", fontsize=20)
    plt.xlabel('Población inicial')
    plt.ylabel('Fitness')
    plt.plot(x, y)
    plt.show()
Example #3
0
 def insertConstant(self, constantValue, constantType, constantAddress):
     if constantValue in self.constants:
         raise Exception(
             "{} already exists in the directory".format(constantValue))
     else:
         c = Constant(constantType, constantAddress)
         self.constants[constantValue] = c
Example #4
0
 def __init__(self, board, SIZE):
     """
     Utilitaire de PlayerEngine
     :param board: Le board (class) avec lequel on effectue la partie en cours.
     :param SIZE: Taille du plateau (côté).
     """
     self.board = board
     self.c = Constant(SIZE)
Example #5
0
 def __init__(self, SIZE):
     """
     Le plateau de jeu est caractérisé par sa taille.
     :param SIZE: Taille du plateau de jeu (côté).
     """
     self.SIZE = SIZE
     self.c = Constant(SIZE)
     self.board = {"d" : SIZE, "grille": ['.']*(SIZE**2)}
Example #6
0
 def __init__(self, disk, name, SIZE):
     """
     Initialize le nom du joueur, son disque et les outils nécéssaire au fonctionnement
     de l'IA.
     :param disk: Soit "X" ou "O".
     :param name: Nom du joueur (str).
     :param SIZE: taille du plateau.
     """
     self.disk = disk
     self.name = name
     self.SIZE = SIZE
     self.c = Constant(SIZE)
Example #7
0
def first_example():
    individuals = 10
    first_operation = Operator(lambda x, y: x + y, '+')
    second_operation = Operator(lambda x, y: x * y, '*')
    operations = [first_operation, second_operation]
    values = [25, 7, 8, 100, 4, 2]
    constants = []
    for value in values:
        constants.append(Constant(value))
    depth = 3
    goal = 459
    show_results(individuals, operations, constants, depth, goal, 2000)
Example #8
0
    def Solve(self):

        if self.method is 'Constant':
            from Constant import Constant
            self.yn = Constant(self.x0, self.y0, self.xn)
        elif self.method is 'Linear':
            from Linear import Linear
            self.yn = Linear(self.x0, self.y0, self.xn)
        elif self.method is 'Polynomial':
            from Polynomial import Polynomial
            self.yn = Polynomial(self.x0, self.y0, self.xn)
        elif self.method is 'Splines':
            from Splines import Splines
            self.yn = Splines(self.x0, self.y0, self.xn)
Example #9
0
def second_example():
    individuals = 10
    first_operation = Operator(lambda x, y: x + y, '+')
    second_operation = Operator(lambda x, y: x - y, '-')
    third_operation = Operator(lambda x, y: x / y, '/')
    fourth_operation = Operator(lambda x, y: x * y, '*')
    operations = [
        first_operation, second_operation, third_operation, fourth_operation
    ]
    values = [25, 7, 8, 100, 4, 2]
    constants = []
    for value in values:
        constants.append(Constant(value))
    depth = 4
    goal = 595
    show_results(individuals, operations, constants, depth, goal, 2000)
Example #10
0
def coef2msb(M):
	"""Calcule le msb de l'argument M. 
	- si M est un scalaire non nul, retourne le msb de M
	- si M est 0, retourne 'NULL'
	- si M est une liste (ou matrice), retourne la liste (ou matrice) des msb des éléments de M"""
	mM=[]
	if not isinstance(M,list) and not isinstance(M,numpy.ndarray):
	#Si M n'est ni une liste ni un tableau numpy
		if M != 0:
			return Constant(M,16).FPF.msb
		else:
			return "NULL"
	else:
	#Si M est une liste ou un tableau numpy, appels récursifs sur les éléments de M
		for i in range(len(M)):
			mM.append(coef2msb(M[i]))
	return mM
Example #11
0
 def get_literal_constant(self):
     tok = self.get_next_token()
     self.match(tok, TokenType.CONST_TOK)
     value = tok.Token.get_lexeme()
     return Constant.__new__(value)
 def get_constant(self):
     Token_Node = self.lex.get_next_token()
     Parser.match(Token_Node, TokenType.CONST_TOK)
     x = int(Token_Node.get_lexeme())
     return Constant(x)
Example #13
0
class PositiveConstantTestCase(unittest.TestCase):
    def setUp(self):
        self.constant = Constant(6)

    def runTest(self):
        assert self.constant.roll().getResults() == [(6,True)], 'incorrect positive value'
Example #14
0
 def setUp(self):
     self.constant = Constant(6)
Example #15
0
 def get_constant(self):
     tok = self.lex.get_next_token()
     Parser.match(tok, TokenType.CONST_TOK)
     value = int(tok.get_lexeme())
     return Constant(value)
Example #16
0
 def getConstant(self):
     tok = self.lex.getNextToken()
     self.match(tok, "CONST_TOK")
     value = int(tok.getLexeme())
     return Constant(value)
Example #17
0
def contraintes(fichier):
	"""A partir d'un fichier .mat, génère le code LaTeX pour l'ensemble des contraintes"""
	# Chargement du fichier
	D = loadmat(fichier)

	# On stocke les éléments du dictionnaire dans des variables
	nt = int(D["l"])
	nx = int(D["n"])
	nu = int(D["m"])
	ny = int(D["p"])
	Z = D["Z"]
	u_m = D["um"]
	u_r = D["ur"]
	dcu = D["dcHu"]
	wcpgu = D["wcpgHu"]
	dce = D["dcHe"]
	wcpge = D["wcpgHe"]

	mZ = coef2msb(Z)

	# Calcul des MSB des variables de sorties (m_var_out) et d'entrées (m_var_in)
	if nu == 1:
		m_var_out = []
		for i in range(nt+nx+ny):
			if abs(u_m*dcu[i] - u_r*wcpgu[i]) > abs(u_m*dcu[i] + u_r*wcpgu[i]):
				diff_out = u_m*dcu[i] - u_r*wcpgu[i]
			else:
				diff_out = u_m*dcu[i] + u_r*wcpgu[i]
			m_var_out.append(Constant(diff_out,16).FPF.msb)
		m_var_in = m_var_out[: (nt+nx)] + [Constant(u_m - u_r,16).FPF.msb]
	else:
		m_var_out = []
		for i in range(nt+nx+ny):
			p = 1
			for j in range(nu):
				if abs(u_m[j]*dcu[i][j] - u_r[j]*wcpgu[i][j]) > abs(u_m[j]*dcu[i][j] + u_r[j]*wcpgu[i][j]):
					diff_out = u_m[j]*dcu[i][j] - u_r[j]*wcpgu[i][j]
				else:
					diff_out = u_m[j]*dcu[i][j] + u_r[j]*wcpgu[i][j]
			p *= diff_out
			m_var_out.append(Constant(p,16).FPF.msb)
		m_var_in = m_var_out[: (nt+nx)] + [Constant(u_m[j] - u_r[j],16).FPF.msb for j in range(nu)]


	# TEX
	wZ = []
	for i in range(1,nt+nx+ny+1):
		if i <= nt :
			L=["w_{%d,%d}^J"%(i,j) for j in range(1,nt+1)] + ["w_{%d,%d}^M"%(i,j) for j in range(1,nx+1)] + ["w_{%d,%d}^N"%(i,j) for j in range(1,nu+1)]
			wZ.append(L)
		elif i <= nt+nx : 
			L=["w_{%d,%d}^K"%(i-nt,j) for j in range(1,nt+1)] + ["w_{%d,%d}^P"%(i-nt,j) for j in range(1,nx+1)] + ["w_{%d,%d}^Q"%(i-nt,j) for j in range(1,nu+1)]
			wZ.append(L)
		else:
			L=["w_{%d,%d}^L"%(i-nt-nx,j) for j in range(1,nt+1)] + ["w_{%d,%d}^R"%(i-nt-nx,j) for j in range(1,nx+1)] + ["w_{%d,%d}^S"%(i-nt-nx,j) for j in range(1,nu+1)]
			wZ.append(L)


	var_out = ["w_{%d}^t"%(i) for i in range(1,nt+1)] + ["w_{%d}^x"%(i) for i in range(1,nx+1)] + ["w_{%d}^y"%(i) for i in range(1,ny+1)]
	var_in = ["w_{%d}^t"%(i) for i in range(1,nt+1)] + ["w_{%d}^x"%(i) for i in range(1,nx+1)] + ["w_{%d}^u"%(i) for i in range(1,nu+1)]


	# Sélection de b :
	print("Voici les msb des variables de sortie :")
	print( m_var_out[-ny:])
	print("\nChoisissez les valeurs pour l'erreur")
	b=[]
	for i in range(ny):
		x=float(raw_input("valeur de b_%d:\t"%(i)))
		if int(x)==float(x):
			b.append(float(2**x))
		else:
			b.append(x)
	print( b)
	

	# Calcul du delta
	d=[]
	for i in range(nt + nx + ny):
		c = 0
		for j in range(nt + nx + nu):
			if Z[i][j] != 0:
				c+=1
		d.append(ceil(log(c,2)))


	# Contraintes de BF
	for i in range(nt + nx + ny):
		for j in range(nt + nx + nu):
			if Z[i][j] != 0:
				print( "%s - %s \geq %d\\\\"%(wZ[i][j], var_out[i], m_var_in[j] + mZ[i][j] - m_var_out[i]+ d[i]+1))


	if ny == 1 :
		A = [[abs(dce[i] + wcpge[i]) for i in range(nt+nx+ny)]]
		D = [[abs(dce[i] - wcpge[i]) for i in range(nt+nx+ny)]]
	else:
		A = [[abs(dce[i][j] + wcpge[i][j]) for j in range(nt+nx+ny)] for i in range(ny)]
		D = [[abs(dce[i][j] - wcpge[i][j]) for j in range(nt+nx+ny)] for i in range(ny)]
	

	A2=[]
	for l in A:
		A2.append(list(l))
	D2=[]
	for l in D:
		D2.append(list(l))


	# Calcul des coeff des contraintes d'erreurs avec majoration (A2 et D2)
	bA=[0]*ny
	bD=[0]*ny
	for i in range(ny):
		for j in range(nt+nx+ny):
			if A2[i][j] == max(A2[i][j],D2[i][j]):
				if A2[i][j] != 0:
					bD[i] += float(D2[i][j])/2**(ceil(log(float(A2[i][j])/b[i],2)))
					D2[i][j] = 0
			else:
				if D2[i][j] != 0:
					bA[i] += float(A2[i][j])/2**(ceil(log(float(D2[i][j])/b[i],2)))
					A2[i][j] = 0

	print( bA)
	print( bD)

	for i in range(ny):
		for j in range(nt+nx+ny):
			# avec majoration
			A2[i][j] = float(A2[i][j])*2**m_var_out[j] / (b[i]-bA[i])
			D2[i][j] = float(D2[i][j])*2**m_var_out[j] / (b[i]-bD[i])
			# sans majoration
			A[i][j] = float(A[i][j])*2**m_var_out[j] / b[i]
			D[i][j] = float(D[i][j])*2**m_var_out[j] / b[i]


	print("\n\nContraintes sans majoration\n")

	for i in range(ny):
		cA = ""
		cD = ""
		for j in range(nt + nx + ny):
			if (A[i][j] != 0) :
				cA += "\\frac{%g}{2^{%s}}"%(A[i][j],var_out[j])
				if (j != nt+nx+ny - 1) and ([A[i][k] for k in range(j+1, nt + nx + ny) if A[i][k] != 0] != []):
					cA += " + "
			if (D[i][j] != 0) :
				cD += "\\frac{%g}{2^{%s}}"%(D[i][j],var_out[j])
				if (j != nt+nx+ny - 1) and ([D[i][k] for k in range(j+1, nt + nx + ny) if D[i][k] != 0] != []):
					cD += " + "
		cA += "\leq 1\\\\"
		cD += "\leq 1\\\\"
		print (cA+"\n")
		print (cD+"\n")


	print ("\n\nContraintes avec majoration\n")

	for i in range(ny):
		cA = ""
		cD = ""
		for j in range(nt + nx + ny):
			if (A2[i][j] != 0) :
				cA += "\\frac{%g}{2^{%s}}"%(A2[i][j],var_out[j])
				if (j != nt+nx+ny - 1) and ([A2[i][k] for k in range(j+1, nt + nx + ny) if A2[i][k] != 0] != []):
					cA += " + "
			if (D2[i][j] != 0) :
				cD += "\\frac{%g}{2^{%s}}"%(D2[i][j],var_out[j])
				if (j != nt+nx+ny - 1) and ([D2[i][k] for k in range(j+1, nt + nx + ny) if D2[i][k] != 0] != []):
					cD += " + "
		cA += "\leq 1\\\\"
		cD += "\leq 1\\\\"
		print (cA+"\n")
		print (cD+"\n")
Example #18
0
 def __init__(self, SIZE):
     """Définit l'utilitaire utilisé par evaluation()"""
     self.SIZE = SIZE
     self.c = Constant(SIZE)
     self.engine = PlayerEngine(Board(SIZE), SIZE)
Example #19
0
 def get_literal_constant(self):
     tok = self.get_next_token()
     self.match(tok, TokenType.CONST_TOK)
     value = tok.Token.get_lexeme()
     return Constant.__new__(value)
Example #20
0
    def starting_board(self):
        """Place les quatres disques initiaux de jeu d'une partie d'Othello."""
        for pos, disk in zip([self.c.POSITION[key] for key in (self.c.NUM_COL[self.SIZE/2 - 1] + str(self.SIZE/2), self.c.NUM_COL[self.SIZE/2] + str(self.SIZE/2 + 1), self.c.NUM_COL[self.SIZE/2 - 1] + str(self.SIZE/2 + 1), self.c.NUM_COL[self.SIZE/2] + str(self.SIZE/2))], "OOXX"): # Initial 4 positions
            self.board["grille"][pos] = disk

    def empty_squares(self):
        """Détermine le nombre de case vides sur le plateau."""
        return self.board["grille"].count(".")

if __name__ == "__main__":
    print "Test de la fonction d'affichage du plateau Board.__str__() :"

    # Test avec un plateau entièrement vide de taille 12x12
    SIZE = 12
    c = Constant(SIZE)
    board_12 = Board(SIZE)
    empty_board = ["."]*(SIZE**2)
    if board_12.__str__() == "    "+ " ".join(c.COL) + "\n" +"\n".join([(" "+str(row+1)+"  "+" ".join(empty_board[i:i+SIZE])) if row+1<10 else str(row+1)+"  "+" ".join(empty_board[i:i+SIZE]) for row, i in enumerate([n*SIZE for n in range(SIZE)])]):
        test = "OK"
    else:
        test = "NOK"
    print "\nboard_12.__str__() = \n{} \nResultat attendu = \n{}".format(board_12, "    "+ " ".join(c.COL) + "\n" +"\n".join([(" "+str(row+1)+"  "+" ".join(empty_board[i:i+SIZE])) if row+1<10 else str(row+1)+"  "+" ".join(empty_board[i:i+SIZE]) for row, i in enumerate([n*SIZE for n in range(SIZE)])]))
    print " ---> test {}".format(test)

    # Test avec un plateau plein 2x2 (positions initiales)
    SIZE = 2
    c = Constant(SIZE)
    board_2 = Board(SIZE)
    board_2.board["grille"] = ["O", "X", "X", "O"]
    filled_board = ["O", "X", "X", "O"]
Example #21
0
 def __init__(self, decayingFunction):
     arm = Constant(0)
     super(RestedRottingConstant, self).__init__(decayingFunction, arm)
Example #22
0
 def __init__(self, rewardFunction):
     arm = Constant(0)
     super(RestlessConstant, self).__init__(rewardFunction, arm)