Exemplo n.º 1
0
def findParentheses (proposition):
    openP=-1
    closeP=-1
    parenthesesUndone=0
    parenthesesCheck=0
    for i in range(len(proposition)):
        if (proposition[i]==')'): #Si encuentro un parentesis que cierra resto uno al contador de pares porque está completo
            parenthesesUndone=parenthesesUndone-1
            closeP=i #Guardo la posicion donde cierro
        if (proposition[i]=='('): #Si encuentro un parentesis que abra sumo uno al contador de pares incompletos porque todavía no encuentro su cierre
            parenthesesUndone=parenthesesUndone+1
            openP=i #Guardo la posicion donde abro
        if (parenthesesUndone < parenthesesCheck):
            exp = proposition[openP+1:closeP] #extraes lo que está dentro de los parentesis
            oldProp=saveOperation(exp) #Guardar expresión
            
            if (closeP== len(proposition)-1): #Si el parentesis que cierra está al final de la proposición
                newProposition = proposition[0:openP] + [oldProp] #Guarda todo
            if (openP==0): #Si abre en el inicio
                newProposition = [oldProp] + proposition[closeP+1:len(proposition)] #Tener la anterior + la parte nueva
            if (openP!=0 and closeP != len(proposition)-1): #Si no es de inicio a fin corto la parte que me importa
                newProposition = proposition[0:openP]+[oldProp]+proposition[closeP:len(proposition)]
            if (findFirst(newProposition, '(')!=-1): #Si todavía hay parentesis seguir haciendo esto de forma recursiva
                findParentheses(newProposition)
            else:
                saveOperation(newProposition)
                op.evaluate() #evaluar las proposiciones
                return
        parenthesesCheck=parenthesesUndone #Reestablecer valores
Exemplo n.º 2
0
def renameExpressions(var,exp): #Renombra expresion
    if(len(v.variables)==1): #Si solo hay una variable
        op.evaluate(v.variables,var) #Evaluala directamente
    for key, values in v.variables.items(): #Si no, recorres cada una y le das su valor
        for i in values:
            if i==var:
                pos=v.variables[key].index(i)
                v.truthTable[exp]=v.tableValues[exp]
                v.variables[key][pos]=exp
                op.evaluate(v.variables[key],key) #Luego evaluas
                return
Exemplo n.º 3
0
 def testEvaluate(self):
     self.assertEqual(evaluate(self.testInput[0]), 26)
     self.assertEqual(evaluate(self.testInput[1]), 437)
     self.assertEqual(evaluate(self.testInput[2]), 12240)
     self.assertEqual(evaluate(self.testInput[3]), 13632)
     self.assertEqual(evaluate(self.testInput[4]), 26335)
     self.assertEqual(evaluate(self.testInput[5]), 90)
     self.assertEqual(evaluate(self.testInput[6]), 588968)
     self.assertEqual(evaluate(self.testInput[7]), 1046)
     self.assertEqual(evaluate(self.testInput[8]), 62673715200)
     self.assertEqual(evaluate(self.testInput[9]), 1000)
Exemplo n.º 4
0
def eliminateParentheses (proposition): #Quito los parentesis de la expresión para no rebuscarlos y quedarme solo con variables y operadores
    openP=findLast(proposition, '(') #Busco el último parentesis que abre
    newProposition=proposition[openP+1:len(proposition)] #Guardo del último parentesis que abre hasta el fin
    closeP=openP+findFirst(newProposition, ')')+1 #Busco el primer parentesis que cierra
    auxiliar=proposition[openP+1:closeP] #Guardo desde el primer parentesis al final sin incluir los parentesis, solo texto
    var=saveOperation(auxiliar)
    
    argument=proposition[0:openP] #Me quedo con lo anterior al parentesis
    argument.append(var) #Añado lo que le quite los parentesis anteriormente
    newProposition=proposition[closeP+1:len(proposition)] 
    argument=argument+newProposition #Guardo lo anterior más el fin que no he checado
    if findFirst(argument, '(') != -1: #Si quedan parentesis
        eliminateParentheses(argument) #Sigo eliminando de manera recursiva
    else:
        saveOperation(argument) #Guardo el argumento sin parentesis
        op.evaluate() #evaluo el argumento
Exemplo n.º 5
0
def maximize(OpType, model, shapes, V, device, ctx, stream):
    # Build features
    S = np.tile(shapes, (V.shape[0], 1))
    X = np.concatenate((S, V), axis=1)
    X = keep_valid(OpType, device, X)
    # Model predictions
    predictions = model.predict(np.log2(X), batch_size=8192, verbose=0)
    pred_idxs = np.argsort(predictions, axis=0)[::-1]
    # Actual evaluation of the few best configurations
    perf, idx = [], []
    for i, pred_idx in enumerate(pred_idxs):
        params = X[pred_idx, :][0].astype(int)
        try:
            y = evaluate(OpType, ctx, stream, params)
        except RuntimeError:
            continue
        #Update
        perf += [y]
        idx += [pred_idx]
        if len(perf) == 100:
            break
    #Return the actual best
    fmax = np.max(perf)
    farg_max = X[pred_idxs[np.argmax(perf)], OpType.Nshapes:]
    return fmax, farg_max[0].astype(np.uint32)
Exemplo n.º 6
0
def maximize(OpType, model, shapes, V, device, ctx, stream):
    # Build features
    S = np.tile(shapes, (V.shape[0], 1))
    X = np.concatenate((S, V), axis=1)
    X = keep_valid(OpType, device, X)
    # Model predictions
    predictions = model.predict(np.log2(X), batch_size=8192, verbose=0)
    pred_idxs = np.argsort(predictions, axis=0)[::-1]
    # Actual evaluation of the few best configurations
    perf, idx = [], []
    for i, pred_idx in enumerate(pred_idxs):
        params = X[pred_idx,:][0].astype(int)
        try:
            y = evaluate(OpType, ctx, stream, params)
        except RuntimeError:
            continue
        #Update
        perf += [y]
        idx += [pred_idx]
        if len(perf)==100:
            break
    #Return the actual best
    fmax = np.max(perf)
    farg_max = X[pred_idxs[np.argmax(perf)],OpType.Nshapes:]
    return fmax, farg_max[0].astype(np.uint32)
Exemplo n.º 7
0
def main():
    metric = MetricComputer()
    metric.process.start()
    cosmos = Cosmos()
    fitnesses = {}
    start = time()
    metric_time, evaluation_time, reduce_time, reproduction_time = 0, 0, 0, 0
    for i in range(10000):
        try:
            if i % 100 == 0:
                print(i)
            # Evaluate population
            deb = time()
            for individual in cosmos.population:
                if individual not in fitnesses:
                    fitnesses[individual] = evaluate(cosmos.environment,
                                                     individual)
            evaluation_time += (time() - deb)
            # Reduce population
            deb = time()
            cosmos.population, cosmos.resources = consume_resources(cosmos)
            reduce_time += (time() - deb)
            # todo : remove deads from fitness
            # Reproduce population
            deb = time()
            new_generation = []
            for individual in cosmos.population:
                new_generation.append(
                    mate(
                        individual,
                        choose_partner(individual, cosmos.population,
                                       fitnesses)))
            cosmos.population += new_generation
            cosmos.resources += DEFAULT_COSMOS_RESOURCE_REGENERATION_RATE
            reproduction_time += (time() - deb)
            deb = time()
            metric.add(cosmos)
            metric_time += (time() - deb)
        except KeyboardInterrupt:
            break
    print("evaluation_time", evaluation_time)
    print("reduce_time", reduce_time)
    print("reproduction_time", reproduction_time)
    print("metric_time", metric_time)
    print("main loop time", time() - start)
    metric.join()
    return cosmos, metric.output_queue.get()
Exemplo n.º 8
0
def benchmarks_impl(i, OpType, nsamples, init_cuda, data, progress):
    # Initialize CUDA context
    device, ctx, stream = init_cuda()
    # Process-specific seed
    np.random.seed(int(time()) + i)
    # Retrieve saved data
    arch = 'sm_' + '_'.join(map(str, device.compute_capability))
    path = mkdir('save/{}/{}/'.format(OpType.id,
                                      arch)) + 'data{}.npz'.format(i)
    X, Y = load(path, [('X', OpType.Nparams), ('Y', 1)])
    # Do not update/realloc X, Y at each iteration
    step = 200
    bufX, bufY = np.empty((step, X.shape[1])), np.empty((step, Y.shape[1]))
    #Generate data
    nvalid = X.shape[0]
    progress[i] = min(nsamples, nvalid)
    while nvalid < nsamples:
        P = generate_valid(OpType, device)
        for params in P:
            #print(params)
            sys.stdout.flush()
            try:
                y = evaluate(OpType, ctx, stream, params)
            except:
                print('Exception for', params)
                pass
            bufX[nvalid % step, :] = params
            bufY[nvalid % step, :] = y
            # Save
            nvalid += 1
            if nvalid % step == 0:
                X = np.vstack((X, bufX))
                Y = np.vstack((Y, bufY))
                np.savez(path, X=X, Y=Y)
            # Update progress
            progress[i] = min(nsamples, nvalid)
            if nvalid > nsamples:
                break
    data[i] = (X, Y)
Exemplo n.º 9
0
def benchmarks_impl(i, OpType, nsamples, init_cuda, data, progress):
    # Initialize CUDA context
    device, ctx, stream = init_cuda()
    # Process-specific seed
    np.random.seed(int(time()) + i)
    # Retrieve saved data
    arch = 'sm_' + '_'.join(map(str, device.compute_capability))
    path = mkdir('save/{}/{}/'.format(OpType.id, arch)) + 'data{}.npz'.format(i)
    X, Y = load(path, [('X', OpType.Nparams), ( 'Y', 1)])
    # Do not update/realloc X, Y at each iteration
    step = 200
    bufX, bufY = np.empty((step, X.shape[1])), np.empty((step, Y.shape[1]))
    #Generate data
    nvalid = X.shape[0]    
    progress[i] = min(nsamples,nvalid)        
    while nvalid < nsamples:
        P = generate_valid(OpType, device)
        for params in P:
            #print(params)
            sys.stdout.flush()
            try:
                y = evaluate(OpType, ctx, stream, params)
            except:
                print('Exception for', params)
                pass
            bufX[nvalid % step, :] = params
            bufY[nvalid % step, :] = y
            # Save
            nvalid += 1
            if nvalid % step == 0:
                X = np.vstack((X, bufX))
                Y = np.vstack((Y, bufY))
                np.savez(path, X=X, Y=Y)
            # Update progress
            progress[i] = min(nsamples,nvalid)
            if nvalid > nsamples:
                break
    data[i] = (X, Y)
Exemplo n.º 10
0
def evaluations(name, container):
    print(str(name) + ' Starting')

    # Memory used for the tree
    memory = []
    # Log list is used to write to the result log after the run
    log_list = []
    # Best solution found during this particular run
    solution = []
    # Best fitness found which corresponds to the best solution found
    solution_fitness = []

    # Holds the highest fitness this particular run
    highest_fitness = 0

    # Places the name at the top of the list for the log file
    log_list.append(name)

    # Create the memory list for the current run
    for num in range(0, container.k):
        x = random.randrange(0, 2, 1)
        y = random.randrange(0, 2, 1)

        # Create the memory for a given run
        memory.append((x, y))

    # Fitness Evaluations begin
    for evals in range(1, container.fitness + 1):
        # Holds the values used to calculate the fitness at the end of an eval
        PfitnessValues = []
        OfitnessValues = []
        # Holds the evals fitness value
        PfitnessValue = 0
        OfitnessValue = 0
        tempP = 0
        tempO = 0

        # This is where the game is actually played
        for play in range(container.l):
            # Creates the tree and a list of the elements in the tree in order that they were created
            tree, tree_list = operations.createTree(container.d, container.k)

            # Reorders the list so that they are in the preordered form
            tree_list = operations.reorder(container.d, tree_list)

            newDecision = operations.evaluate(memory, container.k, tree_list,
                                              container.decision)

            fitnessP, fitnessO = operations.yearsInJail(
                newDecision, container.decision)

            # Set the new tit-for-tat decision
            container.decision = newDecision

            PfitnessValues.append(fitnessP)
            OfitnessValues.append(fitnessO)

            if fitnessP > container.solution_fitness:
                container.solution_fitness = fitnessP
                solution_log = open(container.prob_solution_file, 'w')

                for i in tree_list:
                    solution_log.write(str(i) + " ")

        for value in PfitnessValues:
            tempP += value

        for value in OfitnessValues:
            tempO += value

        PfitnessValue = tempP / len(PfitnessValues)
        OfitnessValue = tempO / len(OfitnessValues)

        if PfitnessValue > highest_fitness:
            highest_fitness = PfitnessValue
            log_list.append((evals, PfitnessValue))

        if evals % 1000 == False:
            print("\n" + str(name) + "\n" + str(evals) + "	" +
                  str(PfitnessValue))

    container.results.append(log_list)

    print(str(name) + ' Exiting')
Exemplo n.º 11
0
def evaluations(name, container):
    print(str(name) + ' Starting')

    # Memory used for the tree
    memory = []
    # parents and parent fitness
    parents = []
    parentFitness = []
    # Log list is used to write to the result log after the run
    log_list = []
    # Best solution found during this particular run
    solution = []
    # Best fitness found which corresponds to the best solution found
    solution_fitness = []

    # Holds the highest fitness this particular run
    highest_fitness = 0

    # Places the name at the top of the list for the log file
    log_list.append(name)

    # Create the memory list for the current run
    for num in range(0, container.k):
        x = random.randrange(0, 2, 1)
        y = random.randrange(0, 2, 1)

        # Create the memory for a given run
        memory.append((x, y))

    #Initialization
    # Play 2k games before counting anything towards fitness
    for game in range(2000):
        # Creates the tree and a list of the elements in the tree in order that they were created
        tree, tree_list = operations.createTree(container.d, container.k)

        # Reorders the list so that they are in the preordered form
        tree_list = operations.reorder(container.d, tree_list)

        newDecision = operations.evaluate(memory, container.k, tree_list)

        fitnessP, fitnessO = operations.yearsInJail(newDecision,
                                                    container.decision)

        # Set the new tit-for-tat decision
        container.decision = newDecision

        parents.append(tree_list)
        parentFitness.append(fitnessP)

        if game % 200 == False:
            print(str(game) + " done")

    # Fitness Evaluations begin
    for evals in range(1, container.fitness + 1):
        # Holds the values used to calculate the fitness at the end of an eval
        PfitnessValues = []
        OfitnessValues = []
        # Holds the evals fitness value
        PfitnessValue = 0
        OfitnessValue = 0
        tempP = 0
        tempO = 0

        highest_fitness = 0

        for generation in range(container.generations):
            # Used for parent selection
            currentParents = []
            currentParentFitness = []

            # Used for survival selection
            offSpring = []
            offSpringFitness = []

            # Parent Selection
            if container.fitnessProportional == 1:
                currentParents, currentParentFitness = operations.fitnessProportional(
                    parents, parentFitness, container.parentNumber)
            elif container.overSelection == 1:
                currentParents, currentParentFitness = operations.OverSelection(
                    parents, parentFitness, container.parentNumber)

            # This is where the game is actually played
            for play in range(container.l):
                # Recombination
                if container.subTree_Crossover_Recombination == 1:
                    tree_list = operations.Recombination(currentParents)

                # Mutation
                if container.subTree_Crossover_Mutation == 1:
                    mutate = random.random()

                    if mutate <= container.mu:
                        operations.mutate(tree_list, container.k)

                newDecision = operations.evaluate(memory, container.k,
                                                  tree_list)

                fitnessP, fitnessO = operations.yearsInJail(
                    newDecision, container.decision)

                # Updates the highest_fitness_value
                if highest_fitness < fitnessP:
                    highest_fitness = fitnessP

                # Set the new tit-for-tat decision
                container.decision = newDecision

                offSpring.append(tree_list)
                offSpringFitness.append(fitnessP)
                PfitnessValues.append(fitnessP)

                if fitnessP > container.solution_fitness:
                    container.solution_fitness = fitnessP
                    solution_log = open(container.prob_solution_file, 'w')

                    for i in tree_list:
                        solution_log.write(str(i) + " ")

            # Survival Selection
            if container.truncation == 1:
                parents, parentFitness = deepcopy(
                    operations.Truncation(offSpring, offSpringFitness,
                                          container.parentNumber))
            elif container.kTournament == 1:
                parents, parentFitness = deepcopy(
                    operations.kTournament(offSpring, offSpringFitness,
                                           container.parentNumber))

            # Termination
            if container.numEvals == 1:
                if generation == (container.terminationEvals - 1):
                    break
            elif container.noChange == 1:
                if operations.noChange(PfitnessValues, container.n):
                    break

        for value in PfitnessValues:
            tempP += value

        averageValue = tempP / len(PfitnessValues)

        log_list.append((evals, averageValue, highest_fitness))

        if evals % 200 == False:
            print("\n" + "Run " + str(name) + "\n" + str(evals) + "	" +
                  str("%.2f" % averageValue) + "	" + str(highest_fitness))

    container.results.append(log_list)

    print(str(name) + ' Exiting')
Exemplo n.º 12
0
def evaluations(name, container):
	print(str(name) + ' Starting')

	# Memory used for the tree
	memory = []
	# parents and parent fitness
	parents = []
	parentFitness = []
	# Log list is used to write to the result log after the run
	log_list = []
	# Best solution found during this particular run
	solution = []
	# Best fitness found which corresponds to the best solution found
	solution_fitness = []

	# Holds the highest fitness this particular run
	highest_fitness = 0

	# Number of evals to pit against one another for the Coevolutionary algorithm
	CoevoOpponents = 0

	# Holds the previous Average Value
	previousAverage = 0

	# Places the name at the top of the list for the log file
	log_list.append(name)

	# Set the CoevoOponents value
	CoevoOpponents = math.floor((container.mu + container.generations - 1) * container.CoevolutionaryFitnessSamplePercent)

	# Create the memory list for the current run
	for num in range(0, container.k):
		x = random.randrange(0, 2, 1)
		y = random.randrange(0, 2, 1)

		# Create the memory for a given run
		memory.append((x, y))


	'''------Initialization------'''
	# (Ramped half-and-half)
	for i in range(container.parentNumber + 1):
		if i < math.floor(container.parentNumber / 2): #------Grow------
			# Get a random depth for the tree
			depth = random.randrange(2, container.d)

			# Create the tree of the randomized depth and a list of the elements in the tree in order that they were created
			tree, tree_list = operations.createTree(depth, container.k)

			# Reorders the list so that they are in the preordered form
			tree_list = operations.reorder(depth, tree_list)

			# The final decision of the Agent this game
			newDecision = operations.evaluate(memory, container.k, tree_list)

			# The fitness calculation of the Agent this game
			fitnessP = operations.yearsInJail(newDecision, container.decision)

			# Set the new tit-for-tat decision
			container.decision = newDecision

			parents.append(tree_list)
			parentFitness.append(fitnessP)

		elif i > math.floor(container.parentNumber / 2): #------Full------
			# Create the tree of the randomized depth and a list of the elements in the tree in order that they were created
			tree, tree_list = operations.createTree(container.d, container.k)

			# Reorders the list so that they are in the preordered form
			tree_list = operations.reorder(container.d, tree_list)

			# The final decision of the Agent this game
			newDecision = operations.evaluate(memory, container.k, tree_list)

			# 
			fitnessP = operations.yearsInJail(newDecision, container.decision)

			# Set the new tit-for-tat decision
			container.decision = newDecision

			parents.append(tree_list)
			parentFitness.append(fitnessP)



	# Play 2k games before counting anything towards fitness
	for game in range(1, 2001):
		# Grab one of the parents and play the game
		tree_list = random.choice(parents)

		# The final decision of the Agent this game
		newDecision = operations.evaluate(memory, container.k, tree_list)

		# Set the new tit-for-tat decision
		container.decision = newDecision

		if game % 500 == False:
			print(str(game) + " done")


	'''------Fitness Evaluations begin------'''
	for evals in range(1, container.fitness + 1, CoevoOpponents):
		# Best composite fitness
		Best_Composite_Fitness = 0
		Average_Composite_Fitness = 0

		# Holds the fitnessList tuple for each Coevolution cycle
		fitnessList = []

		for opponent in range(0, CoevoOpponents):
			# Holds the values used to calculate the fitness at the end of an eval
			PfitnessValues = []
			# Holds the evals fitness value
			PfitnessValue = 0
			tempP = 0

			for generation in range(container.generations):
				# Used for parent selection
				currentParents = []
				currentParentFitness = []

				# Used for survival selection
				offSpring = []
				offSpringFitness = []


				'''------Parent Selection------'''
				if container.fitnessProportional == 1:
					currentParents, currentParentFitness = operations.fitnessProportional(parents, parentFitness, container.parentNumber)
				elif container.overSelection == 1:
					currentParents, currentParentFitness = operations.OverSelection(parents, parentFitness, container.parentNumber)


				# This is where the game is actually played
				for play in range(container.l):
					'''------Recombination------'''
					if container.subTree_Crossover_Recombination == 1:
						tree_list = operations.Recombination(currentParents)


					'''------Mutation------'''
					if container.subTree_Crossover_Mutation == 1:
						mutate = random.random()

						if mutate <= container.mu:
							operations.mutate(tree_list, container.k)


					newDecision = operations.evaluate(memory, container.k, tree_list)

					fitnessP = operations.yearsInJail(newDecision, container.decision)

					# Updates the highest_fitness_value
					if highest_fitness < fitnessP:
						highest_fitness = fitnessP

					# Set the new tit-for-tat decision
					container.decision = newDecision

					offSpring.append(tree_list)
					offSpringFitness.append(fitnessP)
					PfitnessValues.append(fitnessP)

					if fitnessP > container.solution_fitness:
						container.solution_fitness = fitnessP
						solution_log = open(container.prob_solution_file, 'w')

						for i in tree_list:
							solution_log.write(str(i) + " ")


				'''------Survival Strategy Implementation and Survival Selection------'''
				if container.survivalStrategyPlus:
					offSpring = offSpring + parents
					offSpringFitness = offSpringFitness + parentFitness
				elif container.survivalStrategyComma:
					# Parents are automaticaly killed off after this, no implementation for this particular part needed
					pass


				'''------Survival Selection------'''
				if container.truncation == 1:
					parents, parentFitness = deepcopy(operations.Truncation(offSpring, offSpringFitness, container.parentNumber))
				elif container.kTournament == 1:
					parents, parentFitness = deepcopy(operations.kTournament(offSpring, offSpringFitness, container.parentNumber))


				'''------Termination------'''
				if container.numEvals == 1:
					if generation == (container.terminationEvals - 1):
						break
				elif container.noChange == 1:
					if operations.noChange(PfitnessValues, container.n):
						break

			for value in PfitnessValues:
				if value > Best_Composite_Fitness:
					Best_Composite_Fitness = value


				tempP += value

			# Find the average of this play
			PfitnessValue = tempP / len(PfitnessValues)

			# Make a tuple using the average for this play and the Best for this play
			fitnessTuple = (PfitnessValue, Best_Composite_Fitness)

			# Add the tuple to the list in order to computer things later on
			fitnessList.append(fitnessTuple)

		# Now its time to take the fitnessList and find the Average Composite Fitness and Best Composite Fitness
		for fitnessTuple in fitnessList:
			average, best = fitnessTuple

			Average_Composite_Fitness += average
			Average_Composite_Fitness = ((Average_Composite_Fitness + previousAverage) / (len(fitnessList) + 1))

			previousAverage = Average_Composite_Fitness

		for i in range(CoevoOpponents):
			log_list.append((evals + i, Average_Composite_Fitness, Best_Composite_Fitness))

		if evals % 7 == False:
			print("\n" + "Run " + str(name) + "\n" + str(evals) + "	" + str("%.2f" % Average_Composite_Fitness) + "	" + str(Best_Composite_Fitness))

	container.results.append(log_list)

	print(str(name) + ' Exiting')