def __init__(self, popSize): self.p = {} for i in range(0, popSize): self.p[i] = INDIVIDUAL(i)
def Rapture(self): # include a loop to sort p[] based on most to least fit. for i in range(len(self.p), self.popSize): self.p[i] = INDIVIDUAL(i)
def Breed(self, other): p1 = random.randint(0, len(other.p) - 1) # p1 = 0 p2 = random.randint(0, len(other.p) - 1) child = INDIVIDUAL(1) # This only sets up the framework of the child geneImprint = MatrixCreate(len(other.p[p1].genome), len(other.p[p1].genome[0])) geneImprint = MatrixRandomize(geneImprint) childGenome = other.p[p1].genome * geneImprint childGenome += other.p[p2].genome * np.logical_not(geneImprint) child.genome = childGenome return child
def Initialize(self): """ Generates the initial population of individuals. Empty dictionary representing population is filled with desired number of individuals having traits like genome, robot wheel size, mass etc randomly initialized. return: None """ for i in range(0, self.popsize): self.p[i] = INDIVIDUAL(i)
def __init__(self, popSize): # define the constructor self.p = { } # create a single internal variable p which stores a dictionary for i in range(0, popSize): from individual import INDIVIDUAL self.p[i] = INDIVIDUAL(i) # call the INDIVIDUAL constructor
class PARENT(): parent = INDIVIDUAL() parent.Evaluate(True) for i in range(0, 50): child = copy.deepcopy(parent) child.Mutate() child.Evaluate(True) print("[currgen: ", i, "]", "[weight: ", parent.genome, "]", "[p:", parent.fitness, "]", "[c: ", child.fitness, "]") if (child.fitness > parent.fitness): parent = child
def replace(self): temp_class = [] for person in self.pop: print(self.pop[person].ID, self.pop[person].fitness) temp_class.append(self.pop[person]) # Takes the worst performing 10% by their fitness values bad_hombres = sorted(temp_class, reverse=True)[-int(self.popSize * .1):] # Replaces them with new random individuals for hombre in bad_hombres: hombre = int(hombre.ID) self.pop[hombre] = INDIVIDUAL(hombre) self.pop[hombre].age = 0
def apfo(self, other): fill_start = time.clock() keep = [] pop_fitness = [] ages = [] IDs = [] removed = [] # Adds age and IDs for plotting pngs at the end of evolution to track the peritofront. for x in range(len(other.pop)): keep.append(True) IDs.append(other.pop[x].ID) ages.append(other.pop[x].age) pop_fitness.append(other.pop[x].fitness) for y in range(len(other.pop)): # If the indivudual is older and has a lower performance than a younger individual, # than that individual is marked for removal. All individuals in the first population # are excempt to allow them another mutation to imporve. if other.pop[y].fitness > other.pop[x].fitness and \ other.pop[y].age <= other.pop[x].age and other.pop[x].age > 0: keep[x] = False # Retrieves the index of the best indivdual from the population. I don't want to move their # position in the population, only flag their ID for later. best_index = self.retrieve_best_index(other) pop_limit = len(other.pop) # If there is a saturation of the peritofront, I want to add some more individuals, once I # reach a max of 20, then remove the lagging 10% according to fitness. #TODO: Change this, if I remove the bottom 10% in the event of a saturation, then it's # counter to the idea of the afpo. Maybe choose 10% at random to remove? if sum(keep) > len(other.pop) * 0.8: if len(other.pop) < 20: pop_limit = len(other.pop) + 2 self.popSize = pop_limit keep.extend([False, False]) else: other.replace() for n in range(pop_limit): if keep[n]: self.pop[n] = copy.deepcopy(other.pop[n]) # Don't mutate the best individual #TODO: Should this change so all best-performers within each age group are kept? if n != best_index: self.pop[n].Mutate() self.pop[n].increment_age() else: self.pop[n] = INDIVIDUAL(n) self.pop[n].age = 0 removed.append(n) self.pop[n].fitness = 0 print("Removed: ", removed) return pop_fitness, ages, IDs, best_index
import copy import pickle from individual import INDIVIDUAL # import matplotlib.pyplot as plt parent = INDIVIDUAL() parent.Evaluate(False) for g in range(0, 100): child = copy.deepcopy(parent) child.Mutate() child.Evaluate(True) print('[g: ', g, ' ] ', '[pw: ', parent.genome, ' ] ', '[p: ', parent.fitness, ' ] ', '[c: ', child.fitness, ' ]') if child.fitness > parent.fitness: parent = child parent.fitness = child.fitness parent.Evaluate(False) f = open('robot.p', 'wb') pickle.dump(parent, f) f.close() # sensorData = sim.get_sensor_data(sensor_id=P2) # print(sensorData) # f = plt.figure() # panel = f.add_subplot(111) # panel.set_ylim(-1, +2) # plt.plot(sensorData) # plt.show()
def Initialize(self): for i in range(0, self.speciesSize): self.p[i] = INDIVIDUAL(i, self.color, self.eval_time, self.mutationRate, self.position)
import constants as c from individual import INDIVIDUAL def Random_X(): return random.random()*(c.endX-c.startX) + c.startX def Random_Y(): return random.random()*(c.endY-c.startY) + c.startY def Random_Theta(): return random.random()*2.0*math.pi # --------------- Start of the program --------------- ind = INDIVIDUAL() initialX = Random_X() initialY = Random_Y() initialTheta = Random_Theta() ind.Evaluate(initialX,initialY,initialTheta,pp=False,pb=False) print 'total light collected = ' + str(ind.fitness)
import pickle from individual import INDIVIDUAL ''' Instructions: Implement hill climber search https://www.reddit.com/r/ludobots/wiki/pyrosim/hillclimber Blue diamond is the y coordinate ''' plot_flag = True visualize_best = True fitness_robots = [] parent = INDIVIDUAL() parent.evaluate(blind_mode=False) print(parent.fitness) for i in range(100): child = copy.deepcopy(parent) child.mutate() child.evaluate(blind_mode=True) print('[g:{}] - [Pw:{}] - [P:{}] - [c:{}]'.format(i, parent.genome, parent.fitness, child.fitness)) if (child.fitness > parent.fitness): parent = child fitness_robots.append(child.fitness) child.evaluate(blind_mode=True) # Save the strongest model
import random import pyrosim import matplotlib.pyplot as plt from robot import ROBOT import copy import pickle from individual import INDIVIDUAL parent = INDIVIDUAL() parent.evaluate(True) for i in range(0, 100): child = copy.deepcopy(parent) child.mutate() child.evaluate(True) print("[g: %s] [pw: %s] [p: %s] [c: %s]" % (i + 1, parent.genome, parent.fitness, child.fitness)) if child.fitness > parent.fitness: child.evaluate(True) parent = child # f = open("robot.p", "wb") # # pickle.dump(parent, f) # # f.close()
from individual import INDIVIDUAL import copy, pickle # ---------------------- parent = INDIVIDUAL() parent.Evaluate(True) print parent.fitness for g in range(0, 200): child = copy.deepcopy(parent) child.Mutate() child.Evaluate(True) print '[g:', g, ']', print '[pw:', parent.genome, ']', print '[p:', parent.fitness, ']', print '[c:', child.fitness, ']' if (child.fitness > parent.fitness): parent = child
def Initialize(self): for i in range(0, self.popsize): self.p[i] = INDIVIDUAL(i)
import numpy as np import math import pip import pyrosim import random import copy import pickle from snakeservo import ROBOT from individual import INDIVIDUAL from population import POPULATION genvector = np.genfromtxt('bestind.txt', dtype='float') print genvector indbest = INDIVIDUAL(0) indbest.genome = genvector print indbest.genome indbest.Start_Evaluation(False)
from individual import INDIVIDUAL import copy # create instance of class INDIVIDUAL parent = INDIVIDUAL() # evaluate the individual individual.Evaluate() # print the fitness print(individual.fitness) # for loop that creates n iterations for i in range(0, 1): child = copy.deepcopy(parent) print(parent.fitness, child.fitness)
def Initialize(self, genome=None, cppn=None): for i in range(self.popSize): self.pop[i] = INDIVIDUAL(i, genome, cppn)
def __init__(self, popSize, d): self.p = [] self.popSize = popSize for i in range(0, self.popSize): self.p.append(INDIVIDUAL(i, d))
import matplotlib.pyplot as plt from pyrosim import PYROSIM from robot import ROBOT from individual import INDIVIDUAL import copy as cp import pickle import random parent = INDIVIDUAL() for i in range(0,100): child = cp.deepcopy(parent) child.Mutate() parent.Evaluate(hideSim=True) child.Evaluate(hideSim=True) print("[g: ", i, "] [PW: ", parent.genome," ][P: ", parent.fitness, "] [C:", child.fitness, "]") if (child.fitness > parent.fitness): parent = child f = open("robot.p", "wb") pickle.dump(parent, f) f.close() parent.Evaluate(hideSim=False) ######################################################################################################################## # Data Visualization
class GENOME: def __init__(self,ID,fitness=c.worstFitness): self.Set_ID(ID) self.indv = INDIVIDUAL(ID) self.age = 0 self.fitness = fitness def Age(self): self.age = self.age + 1 def Dominates(self,other): if self.Get_Fitness() <= other.Get_Fitness(): if self.Get_Age() <= other.Get_Age(): equalFitnesses = self.Get_Fitness() == other.Get_Fitness() equalAges = self.Get_Age() == other.Get_Age() if not equalFitnesses and equalAges: return True else: return self.Is_Newer_Than(other) else: return False else: return False def Evaluate(self): self.indv.Start_Evaluation(True) f = self.indv.Compute_Fitness() # if f < 0: # self.fitness = c.worstFitness # else: # self.fitness = 1/(1+f) self.fitness = -f def Get_Age(self): return self.age def Get_Fitness(self): return self.fitness def Mutate(self): self.indv.Mutate() def Print(self): print(' fitness: ' , end = '' ) print(self.fitness , end = '' ) print(' age: ' , end = '' ) print(self.age , end = '' ) print() def Save(self,randomSeed): f = open('savedRobots.dat', 'ab') pickle.dump(self.indv , f) f.close() pass def Set_ID(self,ID): self.ID = ID def Show(self): self.indv.Start_Evaluation(False, 40) self.indv.Compute_Fitness() # def __add__(self, other): # total_fitness = self.fitness + other.fitness # print("I've been called") # return GENOME(1, total_fitness) # def __radd__(self, other): # if other == 0: # return self # else: # return self.__add__(other) # -------------------- Private methods ---------------------- def Get_ID(self): return self.ID def Is_Newer_Than(self,other): return self.Get_ID() > other.Get_ID()
import matplotlib.pyplot as plt import pickle from robot import ROBOT from individual import INDIVIDUAL from copy import deepcopy #create objects parent = INDIVIDUAL() print(parent.evaluate(play_blind=True)) for i in range(100): child = deepcopy(parent) child.mutate() print( f'[g: {i}] [pw: {parent.genome}] [p: {parent.fitness}] [c: {child.evaluate(play_blind=True)}]' ) if (child.fitness > parent.fitness): parent = child # f = open('robot.p','wb') # pickle.dump(parent , f ) # f.close() # child.evaluate()
def __init__(self,ID,fitness=c.worstFitness): self.Set_ID(ID) self.indv = INDIVIDUAL(ID) self.age = 0 self.fitness = fitness
def create_population(self): ''' Creates a set of individuals ''' for i in range(self.pop_size): self.p[i] = INDIVIDUAL(i)
def initialize(self): for i in range(self.popSize): self.p[i] = INDIVIDUAL(i, eval_time=self.eval_time)
import random import pyrosim import matplotlib.pyplot as plt from robot import ROBOT from individual import INDIVIDUAL for i in range(0, 10): individual = INDIVIDUAL() individual.evaluate() # sim = pyrosim.Simulator(eval_time=500, play_paused=False) # # robot = ROBOT(sim, random.random()*2-1) # # # Start # # sim.start() # # sim.wait_to_finish() # # # y # sensorData = sim.get_sensor_data(sensor_id=robot.P4, svi=1) # # print(sensorData[-1]) # # # Analyze sensor data # # f = plt.figure() #
def __init__(self, popSize=5, initialize=True): if initialize: self.p = [INDIVIDUAL(i) for i in range(popSize)] else: self.p = []