Beispiel #1
0
    def __init__(self, rep_length, popsize, sp, mut, fitfun, maxgen, cross, nr_processes, run_id , path, onlyThebest, runval):

        self.nr_processes = nr_processes
        self.currentIteration=0
        self.fitfun =fitfun
        self.maxIterations=maxgen
        self.popsize=popsize
        self.cars = []
        self.fitArray = []
        self.onlyTheBest = onlyThebest
        if self.onlyTheBest == 0:
            for i in range(self.popsize):
                self.cars.append(individual.individual(random.uniform(50,150), random.uniform(0,0.1), random.uniform(0,20), random.uniform(0,1), random.uniform(0,100), random.uniform(0,1), random.uniform(0,1), random.uniform(0,70), random.uniform(0,1), random.randint(5000,8000),random.uniform(0,1),random.uniform(50,110),random.uniform(50,110),random.uniform(5,15)))
        print len(self.cars)
        if self.onlyTheBest == 1:
            #total:1339.172; aalborg: 100.808 alpine1: 212.258 alpine2: 143.42 brondehach: 135.83 corkscrew: 120.926 eroad: 95.704 gtrack: 61.342 forza: 156.748 wheel1: 128.67 wheel2: 183.466 parameters: ['154.897575174', '-0.0199', '-0.139884752072', '0.779904990626', '82.8097466274', '0.971351422208', '0.246257782509', '32.9286263315', '0.0215211462875', '5909.19902', '0.829675710924', '78.4693515643', '49.7170137868', '17.9086116398']
            #FAEHRT SICHER aber auf manchen strecken ein wenig langsammer
            self.cars.append(individual.individual('154.897575174', '-0.0199', '-0.139884752072', '0.779904990626', '82.8097466274', '0.971351422208', '0.246257782509', '32.9286263315', '0.0215211462875', '5909.19902', '0.829675710924', '78.4693515643', '49.7170137868', '17.9086116398'))
            #total:1314.005; aalborg: 100.144 alpine1: 202.608 alpine2: 139.396 brondehach: 131.636 corkscrew: 123.965 eroad: 95.432 gtrack: 61.22 forza: 154.07 wheel1: 128.66 wheel2: 176.874 parameters: ['154.897575174', '-0.0199', '-0.0538732272792', '0.779904990626', '82.8097466274', '0.774216279987', '0.246257782509', '32.9286263315', '0.0215211462875', '5909.19902', '0.829675710924', '78.4693515643', '44.6453124081', '17.9086116398']
            #SCHNELLER aber unsicherer
            #self.cars.append(individual.individual('154.897575174', '-0.0199', '-0.0538732272792', '0.779904990626', '82.8097466274', '0.774216279987', '0.246257782509', '32.9286263315', '0.0215211462875', '5909.19902', '0.829675710924', '78.4693515643', '44.6453124081', '17.9086116398'))
        self.tournamentSize=sp
        self.crossoverChance = cross
        self.debug=0
        self.mutationChance = mut
        self.runval=runval
Beispiel #2
0
 def first_generation(self, gen_size, len_behav_seq = 100, seed = None, **kwargs):
     '''
     Initialize first generation
     This function is only used in order to initialize the very first generation!
     For the following generations use the "inherit()" function 
     
     gen_size: Number of Individuals in Generation
     
     Please specify 'opt_behav_seq' (optimal behavioural sequence):
         opt_behav_seq = [---your behav_seq ---]
     
     len_behav_seq (optional): The length of the behavioural sequences
     seed (optional): If a seed is given, the run can be reproduced using the exact same seed 
     '''
     
     # SEEDING
     self.__seed = seed
     
     if self.__seed != None:
         seed_list1 = generation.__create_seed_list(gen_size * 100, self.__seed)
         #Creating a second seed list
         seed_list2 = generation.__create_seed_list(gen_size, self.__seed + 1111)
         seed_list3 = generation.__create_seed_list(gen_size, self.__seed + 2222)
         
 
     #Start of the real function
     
     ind_list = []
     for i in range(gen_size):
         if self.__seed != None:
             ind_seed_list = seed_list1[i*100 : (i+1)*100]
             ind = individual.individual(seed_list = ind_seed_list)
             np.random.seed(seed_list2[i])
             
         else:
             ind = individual.individual()
         #Initialize genotype    
         ind.genotype = np.random.uniform(low = 0.0, high = 1.0)
                
         #Initialize behav_seq
         if self.__seed != None:
             np.random.seed(seed_list3[i])
         ind.behav_seq = list(np.random.uniform(low = 0.0, high = 1.0, size = len_behav_seq))
          
         ind_list.append(ind)
         
     
     self.ind_list = ind_list
     self.do_calculations(**kwargs)
     self.__create_env_change_ind_life(**kwargs)
     self.__simulate_env_change_ind_life(**kwargs)
Beispiel #3
0
	def initialize(self):
		for i in range(self.pop_size):		
			temp=individual.individual(self.chrom_size)
			temp.populate(self.search_space)
			# print("Generated chromosomes: ")
			# print(temp.getChromosome())
			self.chrom_set.append(temp)
Beispiel #4
0
 def initPopulation(self):
     self.lives = []
     for i in range(self.lifeCount):
         gene = [x for x in range(self.geneLength)]
         random.shuffle(gene)
         life = individual(gene)
         self.lives.append(life)
    def restart(self):
        dist = None
        # Individual
        indivi = None

        self.w1 = 0.0
        #self.idivi_list.sort(key = lambda x:x.fitness)
        #sorted(self.idivi_list)
        self.idivi_list.sort(key=lambda x: x.fitness, reverse=True)
        indivi = self.idivi_list[0].clone()
        """
        for i in range(0,len(indivi.geneR)):
            print("After self.idivi_list[0].clone() the indivi.geneR["+str(i)+"] is "+str(indivi.geneR[i]))
        """
        indivi.set_w1(self.w1)

        self.idivi_list.clear()
        self.idivi_list.append(indivi)

        for i in range(1, self.pop_size):
            indivi = individual()
            indivi.init_three(self.rule_base, self.data_base, self.w1)
            indivi.random_values()
            self.idivi_list.append(indivi)

        self.evaluate(0)
        self.L = self.lini
Beispiel #6
0
def initPop(cityList):
    population = []
    for i in range(POPSIZE):
        ind = individual(CHROMSIZE)
        ind.initRandom(cityList)
        population.append(ind)
    return population
Beispiel #7
0
def generate_population(number = 100):
    assert(number > 0), "Population needs to be greater than 0"
    population = {}
    for _ in xrange(number):
        pop = individual([uniform(1, MAX) for _ in xrange(2)])
        population[pop.id] = pop
    return population
 def init_here(self):
     #print("init_here,  initial a new indIn clone of individual, copy the self.geneR6 isividual ......")
     ind = individual()
     ind.init_three(self.rule_base, self.data_base, self.w1)
     ind.reset()
     self.idivi_list.append(ind)
     #print("self.pop_size in init_here for add how many individual into idivi_list is :"+ str(self.pop_size))
     for i in range(1, int(self.pop_size)):
         #print("in loop initial a new individual ......")
         ind = individual()
         ind.init_three(self.rule_base, self.data_base, self.w1)
         ind.random_values()
         #print("going to add a new individual ......")
         self.idivi_list.append(ind)
     #print(" how many idividuals were added in self.idivi_list : "+ str(len(self.idivi_list)))
     self.best_fitness = 0.0
     self.nTrials = 0
Beispiel #9
0
	def init_population(self):
		
		for i in range(self.subnum):
			ind = individual(self.file_name)
			ind.randomize()
			ind.get_obj()								#每次随机化后就生成目标函数的值
			self.update_reference_point(ind)
			self.dict_sub[i].individual = deepcopy(ind)
			self.updateEP(ind)
			self.FunEvals += 1
		print "init_population done!"
Beispiel #10
0
    def generate_individuals(self):
        nov_map = novelty_map(self.novelty_map_size)
        survives = []

        for gene in self.population:
            ind = individual(gene,self.excitation_threshold)
            yield ind
            #exclude fitness:nan
            if math.isnan(ind.fitness):
                continue
            #add survives
            gene.fitness = ind.fitness
            survives.append(gene)
            nov_map.add_node(gene)

        self.mutation(self.select_parents(survives, list(nov_map.nodes())))
Beispiel #11
0
    def newChild(self):
        #产生新个体
        parent1 = self.getOne()
        rate = random.random()
        if rate <= self.crossRate:
            parent2 = self.getOne()
            gene = self.cross(parent1, parent2)
        else:
            gene = parent1.gene

        #突变
        rate = random.random()
        if rate <= self.mutationRate:
            gene = self.mutation(gene)

        #根据新的基因返回一个新的对象
        return individual(gene)
Beispiel #12
0
 def __init__(self, ratio, n, seed=None, distance=None):
     if distance is None:
         distance = 0.1
     if seed is None:
         seed = Random(10001)
     self.length = n
     self.ratio = ratio
     self.stack = np.empty((n), dtype=object)
     self.seed = seed
     self.distance = distance
     for i in range(n):
         if i < ratio * n:
             gender = 'male'
         else:
             gender = 'female'
         self.stack[i] = ind.individual(i,
                                        gender,
                                        seed=seed,
                                        distance=distance)
Beispiel #13
0
 def add_profile(self,
                 gender,
                 hotness=None,
                 threshold=None,
                 distance=None,
                 seed=None,
                 move=True,
                 move_x=None,
                 move_y=None):
     if distance is None:
         distance = self.distance
     if seed is None:
         seed = self.seed
     temp = ind.individual(self.length, gender, hotness, threshold,
                           distance, seed)
     if move:
         temp.move(move_x, move_y)
     self.stack.append(temp)
     self.length = self.length + 1
def load_population(gen):
    with open(f'population-gen-{gen}.yaml', 'r') as f:
        reload = yaml.safe_load(f)
    reload_population = []
    for individual_id in reload:
        ind = individual()
        ind.id = individual_id
        ind.genes = reload[individual_id]['genes']
        ind.j_fluc = reload[individual_id]['j_fluc']
        ind.j_act = reload[individual_id]['j_act']
        ind.j_total = reload[individual_id]['j_total']
        ind.sensor = reload[individual_id]['sensor']
        ind.revolutions = reload[individual_id]['revolutions']
        # Needs to be np array not just regular list.
        ind.revolutions[0] = np.asarray(ind.revolutions[0])
        ind.revolutions[1] = np.asarray(ind.revolutions[1])
        ind.revolutions[2] = np.asarray(ind.revolutions[2])

        reload_population.append(ind)

    return reload_population
Beispiel #15
0
    convergence = 0
    done = False
    fitCheck = 0

    #mutationRate = uniform(0.051, 0.058)
    #popSize = randrange(30,200,2)
    #generationLimit = randrange(50,10000)

    #Population lists
    population = []
    offspring = []

    # INITIALISE and EVALUATE: Random genes for initial population
    for genes in range(popSize):
        # INITIALISE
        indiv = individual()
        indiv.BinGeneCreateInit(chromosomeAmount)
        population.append(indiv)

    #Best gene initialised
    best = population[0]
    newBest = population[0]

    #REPEAT UNTIL DONE - Main loop
    while generation < generationLimit:
        #Reset average fitness, increment generation count
        avgFitness = 0.0
        generation = generation + 1
        print('Gen = ', generation)

        #1 SELECT parents
def cross_mut(mate_pool,mut_prob,mut_type,g,G,limit,n_genes):
    child = individual()
    p0 = 0
    p1 = 0
    counter = 0
    while p0 == p1:
        p0 = random.choice(mate_pool)
        p1 = random.choice(mate_pool)

   #loop protection
    if counter > limit:
        return None

    #arithmetic crossover
    for motor in range(3):
        for key in gene_keys:
            bias = random.uniform(0, 1 + offset)
            gene = bias * p0.genes[key][motor] + (1-bias) * p1.genes[key][motor]
            gene = sat_lim(gene = gene,key = key)
            child.genes[key].append(gene)
    #mutation
    mut_check = random.uniform(0,1)
    r = random.uniform(0,1+offset)
    tau = random.choice([-1,1])

    if mut_check < mut_prob:
        if mut_type == 'all':
            for motor in range(3):
                for key in gene_keys:
                    mut_gene = child.genes[key][motor] + tau*(u_bound[key] - l_bound[key])*(1-r**(g/G))
                    if key == 'frequency':
                        mut_gene = child.genes[key][motor] + tau * (u_bound[key] - 0) * (1 - r ** (g / G))
                    mut_gene = sat_lim(gene = mut_gene,key = key)
                    child.genes[key][motor] = mut_gene

        if mut_type == 'motor':
            motor = random.choice(range(3))
            for key in gene_keys:
                mut_gene = child.genes[key][motor] + tau * (u_bound[key] - l_bound[key]) * (1 - r ** (g / G))
                if key == 'frequency':
                    mut_gene = child.genes[key][motor] + tau * (u_bound[key] - 0) * (1 - r ** (g / G))
                mut_gene = sat_lim(gene=mut_gene, key=key)
                child.genes[key][motor] = mut_gene

        if mut_type == 'gene':
            motor = random.choice(range(3))
            key = random.choice(gene_keys)
            mut_gene = child.genes[key][motor] + tau * (u_bound[key] - l_bound[key]) * (1 - r ** (g / G))
            if key == 'frequency':
                mut_gene = child.genes[key][motor] + tau * (u_bound[key] - 0) * (1 - r ** (g / G))
            mut_gene = sat_lim(gene=mut_gene, key=key)
            child.genes[key][motor] = mut_gene

        if mut_type == 'n_genes':
            shuffled_motors = list(range(3))
            shuffled_keys = gene_keys.copy()
            for _ in range(3):
                random.shuffle(shuffled_motors)
                random.shuffle(shuffled_keys)
            mut_counter = 0
            while mut_counter <= n_genes:
                for motor in shuffled_motors:
                    for key in shuffled_keys:
                        mut_counter += 1
                        mut_gene = child.genes[key][motor] + tau*(u_bound[key] - l_bound[key])*(1-r**(g/G))
                        if key == 'frequency':
                            mut_gene = child.genes[key][motor] + tau * (u_bound[key] - 0) * (1 - r ** (g / G))
                        mut_gene = sat_lim(gene=mut_gene, key=key)
                        child.genes[key][motor] = mut_gene

        if mut_type == 'rand_genes':
            shuffled_motors = list(range(3))
            shuffled_keys = gene_keys.copy()
            for _ in range(3):
                random.shuffle(shuffled_motors)
                random.shuffle(shuffled_keys)

            mut_counter = 0
            rand_genes = random.choice(list(range(1,12)))
            while mut_counter <= rand_genes:
                for motor in shuffled_motors:
                    for key in shuffled_keys:
                        mut_counter += 1
                        mut_gene = child.genes[key][motor] + tau*(u_bound[key] - l_bound[key])*(1-r**(g/G))
                        if key == 'frequency':
                            mut_gene = child.genes[key][motor] + tau * (u_bound[key] - 0) * (1 - r ** (g / G))
                        mut_gene = sat_lim(gene=mut_gene, key=key)
                        child.genes[key][motor] = mut_gene

    return child
Beispiel #17
0
    def __genetic_inheritance(self, prev_gen, mutation_var = 0.001, selection_dist_genotype = "lin"):
        self.__seed = prev_gen.__seed
        
        gen_size = len(prev_gen.ind_list) 
        prev_ind_list = prev_gen.ind_list
        
        if self.__seed != None:
            seed_list4 = generation.__create_seed_list(gen_size, self.__seed + 3333)

        #original order of fitnesses of individuals
        try:
            fit_orig_order = prev_gen.attrs_tolist("fitness")
            
        except AttributeError:
            raise AttributeError('''
                                 The individuals of a generation don't have a 
                                 'fitness' as an attribute. In order to calculate
                                 it run --generation_object--.do_calculatins()
                                 ''')
            
        fit_orig_order = np.array(fit_orig_order)
        
        #create array that would sort fit_orig_order
        sort_arr = np.argsort(fit_orig_order)
        #invert sort_arr for descending order
        sort_arr = sort_arr[::-1] 
        
        ### inheritance of genotype ###
        new_ind_list = []
        for i in range(gen_size):
            new_ind = individual.individual()
            if self.__seed != None:
                np.random.seed(seed_list4[i])

            if selection_dist_genotype == "lin":
                index_sort_arr = np.array(np.random.triangular(0, 0, len(sort_arr)), dtype = int)
                
            elif selection_dist_genotype == "exp":
                # Exponential random parameter is used, making it most likely that 
                # genetic information of fittest individual is inherited
            
                index_sort_arr = np.array(np.random.exponential(scale = len(sort_arr) / 8 ), dtype = int)
                
                #in case calculated index exceeds index of sort_arr, try again:
                ct = 0
                while index_sort_arr >= (len(sort_arr) - 1) :
                    print("exp rand par exceeded   ", len(sort_arr) )
                    #!!!!!!LÖSUNG FÜR SEEDS SUCHEN, am besten fetten stack bauen für jedes individuum!!!!!!!
                    #if ct == 0:
                     #   raise Warning("No Seed used -- run not reproducable")
                    index_sort_arr = np.array(np.random.exponential(scale = len(sort_arr) / 8), dtype = int)
                    ct += 1
                    if ct == 500:
                        raise RuntimeWarning("Caught up in while loop")
           
            # The index in the sort_arr, that we chose is the index - or number of -individual-
            # in the original order that we chose to inherit genotype from (to be the parent)
            index_orig_order = sort_arr[index_sort_arr]
            parent_ind = prev_ind_list[index_orig_order]
            new_ind.gen_genotype(parent_ind, mutation_var)
            new_ind_list.append(new_ind)
        
        self.ind_list = new_ind_list
Beispiel #18
0
def generate_population(num_individuals, ind_size):
	generated_pop = list()
	for _ in xrange(num_individuals):
		generated_pop.append(
			individual.individual(ind_size, MINIMIZE, INDEX_RANGE))
	return generated_pop
Beispiel #19
0
    def crossMutateRun(self):
        """Crosses traits from surviving individuals to regenerate population,
            then runs the new individuals to evaluate their cost.
        """
        # Loop until population has been replenished.
        # Extract the number of individuals.
        n = len(self.individualsList)
        #chooseCount = []
        while len(self.individualsList) < self.numInd:
            if random.random() < self.probabilities['cross']:
                # Since we're crossing over, we won't force a mutation.
                forceMutate = False

                # Prime loop to select two unique individuals. Loop ensures
                # unique individuals are chosen.
                _individualsList = [0, 0]
                while _individualsList[0] == _individualsList[1]:
                    # Pick two individuals based on cumulative weights.
                    _individualsList = random.choices(self.individualsList[0:n],
                                                      weights=\
                                                        self.rouletteWeights,
                                                      k=2)
                # Keep track of who created these next individuals.
                parents = (_individualsList[0].uid, _individualsList[1].uid)
                self.log.debug(('Individuals {} and {} selected for ' +
                                'crossing').format(parents[0], parents[1]))

                # Cross the regulator chromosomes
                regChroms = crossChrom(chrom1=_individualsList[0].regChrom,
                                       chrom2=_individualsList[1].regChrom)
                self.log.debug('Regulator chromosomes crossed.')

                # Cross the capaictor chromosomes
                capChroms = crossChrom(chrom1=_individualsList[0].capChrom,
                                       chrom2=_individualsList[1].capChrom)
                self.log.debug('Capacitor chromosomes crossed.')

            else:
                # We're not crossing over, so force mutation.
                forceMutate = True
                # Draw an individual.
                _individualsList = random.choices(self.individualsList[0:n],
                                                  weights=self.rouletteWeights,
                                                  k=1)

                # Track parents
                parents = (_individualsList[0].uid, )
                self.log.debug(('No crossing, just mutation of individual ' +
                                '{}'.format(parents[0])))

                # Grab the necessary chromosomes, put in a list
                regChroms = [_individualsList[0].regChrom]
                capChroms = [_individualsList[0].capChrom]

            # Track chosen individuals.
            """
            for i in _individualsList:
                uids = [x[1] for x in chooseCount]
                if i.uid in uids:
                    ind = uids.index(i.uid)
                    # Increment the occurence count
                    chooseCount[ind][2] += 1
                else:
                    chooseCount.append([i.fitness, i.uid, 1])
            """

            # Possibly mutate individual(s).
            if forceMutate or (random.random() < self.probabilities['mutate']):
                # Mutate regulator chromosome:
                regChroms = mutateChroms(c=regChroms,
                                         prob=self.probabilities['regMutate'])
                self.log.debug('Regulator chromosome(s) mutated.')
                # Mutate capacitor chromosome:
                capChroms = mutateChroms(c=capChroms,
                                         prob=self.probabilities['capMutate'])
                self.log.debug('Capacitor chromosome(s) mutated.')

            # Create individuals based on new chromosomes, add to list, put
            # in queue for processing.
            for i in range(len(regChroms)):
                # Initialize new individual
                uid = self.popMgr.getUID()
                ind = individual(
                    **self.indInputs,
                    uid=uid,
                    regChrom=regChroms[i],
                    capChrom=capChroms[i],
                    parents=parents,
                )
                self.log.debug('New individual, {}, initialized'.format(uid))
                # Put individual in the list and the queue.
                self.individualsList.append(ind)
                self.addToModelQueue(individual=ind)
                self.log.debug(
                    ('Individual {} put in the model ' + 'queue.').format(uid))
        """
Beispiel #20
0
    def initializePop(self):
        """Method to initialize the population.
        
        TODO: Make more flexible.
        """
        # Create baseline individual.
        if self.baseControlFlag is not None:
            # Set regFlag and capFlag
            if self.baseControlFlag:
                # Non-zero case --> volt or volt_var control
                regFlag = capFlag = 3
            else:
                # Manual control, use 'newState'
                regFlag = capFlag = 4

            # Add a baseline individual with the given control flag
            self.individualsList.append(
                individual(**self.indInputs,
                           uid=self.popMgr.getUID(),
                           regFlag=regFlag,
                           capFlag=capFlag,
                           controlFlag=self.baseControlFlag))

            # Track the baseline individual's index.
            self.baselineIndex = len(self.individualsList) - 1
            self.log.debug('Baseline individual created and added to list.')

        # Create 'extreme' indivuals - all caps in/out, regs maxed up/down
        # Control flag of 0 for manual control
        for n in range(len(CAPSTATUS)):
            for regFlag in range(2):
                ind = individual(**self.indInputs,
                                 uid=self.popMgr.getUID(),
                                 regFlag=regFlag,
                                 capFlag=n,
                                 controlFlag=0)
                self.individualsList.append(ind)
        self.log.debug("'Extreme' individuals created.")

        # Create individuals with biased regulator and capacitor positions
        # TODO: Stop hard-coding the number.
        for _ in range(4):
            ind = individual(**self.indInputs,
                             uid=self.popMgr.getUID(),
                             regFlag=2,
                             capFlag=2,
                             controlFlag=0)
            self.individualsList.append(ind)
        self.log.debug("'Biased' individuals created.")

        # Randomly create the rest of the individuals.
        while len(self.individualsList) < self.numInd:
            # Initialize individual.
            ind = individual(**self.indInputs,
                             uid=self.popMgr.getUID(),
                             regFlag=5,
                             capFlag=5,
                             controlFlag=0)
            self.individualsList.append(ind)
        self.log.debug("Random individuals created.")

        self.log.info('Population initialized.')
Beispiel #21
0
    def step(self):
        self.tempArray = [i for i in range(len(self.cars))]
        self.getFitnessValues()
        for replacer in range (len(self.cars)):
            self.numberOfElites = (int((1-self.crossoverChance)*self.popsize))+2
            if  replacer < self.numberOfElites: ##keep the elites
                self.tempArray[replacer] = self.cars[self.returnFittest()]
                pass
            else:
                for i in range(0,self.tournamentSize):##select parents in tournament
                    self.parent1 = 9999999
                    self.parent2 = 9999999
                    self.randomPos = random.randint(0, len(self.fitArray)-1)
                    while(self.fitArray[self.randomPos] == -1):
                        #print "-1.. get a new one"
                        self.randomPos = random.randint(0, len(self.fitArray)-1)
                    if self.parent1==9999999:
                        self.parent1=self.randomPos
                    elif self.fitArray[self.randomPos] < self.fitArray[self.parent1]:
                        if self.fitArray[self.randomPos] == -1:
                            pass
                        else:
                            self.parent1=self.randomPos
                    self.randomPos = random.randint(0, len(self.fitArray)-1)
                    while(self.fitArray[self.randomPos] == -1):
                        self.randomPos = random.randint(0, len(self.fitArray)-1)
                    if self.parent2==9999999:
                        self.parent2=self.randomPos
                    elif self.fitArray[self.randomPos] < self.fitArray[self.parent2]:
                        if self.fitArray[self.randomPos] == -1:
                            pass
                        else:
                            self.parent2=self.randomPos
                self.tempArray[replacer]=individual.individual(self.cars[self.parent1].values[0],self.cars[self.parent2].values[1], self.cars[self.parent1].values[2], self.cars[self.parent2].values[3], self.cars[self.parent1].values[4], self.cars[self.parent2].values[5], self.cars[self.parent1].values[6], self.cars[self.parent2].values[7],self.cars[self.parent1].values[8],self.cars[self.parent2].values[9],self.cars[self.parent1].values[10],self.cars[self.parent2].values[11],self.cars[self.parent1].values[12], self.cars[self.parent2].values[13] )

        for i in range(len(self.cars)):
            self.cars[i] = self.tempArray[i]

        for i in range(self.numberOfElites, len(self.cars)):
            for gene in range(14):
        #        print "mutating "+str(i)
                if (random.uniform(0, 1) <= self.mutationChance):
                    muval = (self.cars[i].values[gene] * 0.1)+0.1 #random.uniform(-0.1,0.1)

                    if (random.uniform(0,1) <= 0.5):
                       muval = muval*-1
                    self.cars[i].values[gene] = self.cars[i].values[gene] + muval
                    self.cars[i].parameters[gene] = str(float(self.cars[i].parameters[gene]) + muval)
                    pass
        self.cars[0]=self.cars[self.returnFittest()]
        if self.currentIteration == 0:
           print "----------------------------------------------"
           print "run "+str(self.runval)+" starts here"
        print "run: "+str(self.runval)+" generation: "+str(self.currentIteration)+" fittest at: "+str(self.returnFittest())+" its fitness: "+str(self.returnFittestFitness())
        print "it's values:  "+str(self.returnFittestValues())
        print "pop avg fitn: "+str(self.returnAvgFitness())
        print "fitnessarray: "+str(self.fitArray)
        print "number of invalids: "+str(self.invalid)
        print"\n\n"
        bashCommand = "killall torcs-bin"
        os.system(bashCommand)
        print "killed old torcs processes"

        f = open("debugline_wheel2_aal_forza_eroad_street_alpine1.csv","a")
        f.write("run: "+str(self.runval)+" generation: "+str(self.currentIteration)+" fittest at: "+str(self.returnFittest())+" its fitness: "+str(self.returnFittestFitness())+"\n")
        f.close

        f = open("june14_aal_wheel2_aal_forza_eroad_street_alpine1.csv","a") #opens file with name of "test.txt"
        if self.currentIteration == 0:
            f.write(("\n\n\n\n"))
            f.write(("run "+str(self.runval)+" starts here\n"))
        f.write("generation;   "+str(self.currentIteration)+"; ")
        f.write("it's values;  "+str(self.returnFittestValues())+"; number of invalids;"+str(self.invalid)+" ; ")
        f.write("fitnessarray; "+str(self.fitArray)+"; ")
        f.write("pop avg fitn; "+str(self.returnAvgFitness())+"; ")
        f.write("fittest at;   "+str(self.returnFittest())+";  its fitness; "+str(self.returnFittestFitness())+";\n ")
        if self.currentIteration >= self.maxIterations:
            f.write(("the end:\n\n\n\n\n"))
        f.close

        self.currentIteration=self.currentIteration+1
        if self.currentIteration >= self.maxIterations:
            self.stop_reached = True
def genesis(size):
    population = [individual() for _ in range(size)]
    population = genes(population = population)
    return population
Beispiel #23
0
def main():
    global CHROMSIZE

    filename = sys.argv[1]
    seed = sys.argv[2]
    saveFile = "outfile" + seed
    outData = []

    #cityList = openFile('tsps/burma14.tsp')
    cityList = openFile(filename)
    CHROMSIZE = len(cityList)

    random.seed(seed)

    # create initial population with random strings
    pop = initPop(cityList)

    # get fitnesses for population
    evaluate(pop)

    # test print
    # for ind in pop:
    # 	print ind.fitness

    # reproduce, double population via random selection and etc, for each generation
    for i in range(GENERATIONS):
        #print "Gen:", i
        #crossover double pop
        for j in range(LAMBDA / 2):
            parent1 = getRandomIndividual(pop)
            parent2 = getRandomIndividual(pop)
            child1 = individual(CHROMSIZE)
            child2 = individual(CHROMSIZE)
            child1.chrom, child2.chrom = crossover(parent1.chrom,
                                                   parent2.chrom)

            # add new children to population
            pop.append(child1)
            pop.append(child2)

        # eval new members of population
        evaluate(pop)

        # sort pop in place based on lowest distance (counts as highest fitness)
        pop.sort(key=lambda individual: individual.fitness)

        # print "more before cull"
        # for ind in pop:
        # 	print ind.fitness

        # remove excess population
        pop[POPSIZE:] = []
        # print "aftercull"
        # for ind in pop:
        # 	print ind.fitness

        # append new generation info to out data
        genInfo = [i, minDistance(pop), avgDistance(pop), maxDistance(pop)]
        if i % 50 == 0:
            print genInfo

        outData.append(genInfo)

    pickle.dump(outData, open(saveFile, 'w'))
Beispiel #24
0
            lives1 -= 1

        if f == [0, 0]:
            if lives1 == 0:
                f[0] = -2
                f[1] = 1
                return f
            elif lives2 == 0:
                f[1] = 1
                f[0] = -2
                return f

    return f


pop = [individual() for i in range(150)]  #creates a bunch of blank individuals
fitnesses = [0] * 150

global innoNum

for indi in pop:
    for i in range(10):
        innoNum = indi.mutateStructure(150, innoNum)

#store each of the different species
specs = []

for i in range(len(pop)):
    for spec in specs:
        if delta(pop[i], pop[spec[0]]) < dt:
            spec.append(i)
Beispiel #25
0
	def init_reference_point(self):
		ind = individual(self.file_name)
		ind.randomize()
		ind.get_obj()
		self.update_reference_point(ind)
		print "init_reference_point done!"