Пример #1
0
    def update(self,pop):
        sz = len(pop)
        if not sz:
            raise GAError('srs_selector - the pop size is 0!')
        f =pop.fitnesses()
        f_max = max(f); f_min = min(f)
        if not ( (f_max >= 0. and f_min >= 0.) or
                   (f_max <= 0. and f_min <= 0.)):
            raise GAError('srs_selector requires all fitnesses values to be either strictly positive or strictly negative - min %f, max %f' %(f_min,f_max))
        f_avg = sum(f,axis=0)/sz
        if f_avg == 0.:
            e = np.ones_like(f)
        else:
            if pop.min_or_max() == 'max':
                e = f/f_avg
            else:
                e = (-f+f_max+f_min)/f_avg
        self.expected_value = e
        garauntee,chance = divmod(e,1.)
#               garauntee = floor(e)
#               chance = remainder(e,1)
        choices = []
        for i in xrange(sz):
            choices = choices + [pop[i]] * int(garauntee[i])
        #now deal with the remainder
        dart_board = np.add.accumulate(chance / sum(chance,axis=0))
        for i in range(len(choices),sz):
            dart = prng.random()
            idx = 0
            while dart > dart_board[idx]:
                idx = idx + 1
            choices.append(pop[idx])
        self.choices = choices
Пример #2
0
    def mutate(self):
        """
            Returns 1 if gene mutated, 0 otherwise.

            Calls the **mutator.evaluate()** function to mutate the gene
            mutation_rate of the time. Otherwise, it does nothing.
        """
        #inlined 'flip_coin' for speed
        if prng.random() < self.mutation_rate:
            self._value = self.mutator.evaluate(self)
            return 1
        return 0
Пример #3
0
 def select(self,pop,cnt = 1):
     returns = []
     for i in range(cnt):
         dart = prng.random()
         idx = 0
         #binary search would be faster
         while dart > self.dart_board[idx]:
             idx = idx + 1
         returns.append(self.pop[idx])
     if cnt == 1:
         return returns[0]
     else:
         return returns
Пример #4
0
def flip_coin(p):
    """ Return True with probability p.
    """
    return (prng.random() < p)