示例#1
0
 def cross_over(self):
     self.sons = []
     for i in range(self.pop_size):  # create empty sons
         ind = Individual(nvar=self.n_var,
                          nbits=self.bits_per_variable,
                          ncal=self.n_cal)
         self.sons.append(deep_copy(ind))
     for i in range(0, self.pop_size,
                    2):  # cross over and fill their binary code
         for j in range(self.n_var):
             r = random.randint(1, self.bits_per_variable)
             gray_code_father_1 = gc.bin_to_gray(
                 self.fathers[i].binary_code[j])
             gray_code_father_2 = gc.bin_to_gray(
                 self.fathers[i + 1].binary_code[j])
             gray_code_son_1 = [
                 gray_code_father_1[0:r], gray_code_father_2[r:]
             ]
             gray_code_son_1 = ''.join(gray_code_son_1)
             gray_code_son_2 = [
                 gray_code_father_2[0:r], gray_code_father_1[r:]
             ]
             gray_code_son_2 = ''.join(gray_code_son_2)
             self.sons[i].binary_code.append(
                 gc.gray_to_bin(gray_code_son_1))
             self.sons[i + 1].binary_code.append(
                 gc.gray_to_bin(gray_code_son_2))
def chrom_to_real(c):
    indasstring=''.join(map(str, c))
    degray=gray_to_bin(indasstring)
    numasint=int(degray, 2) # convert to int from base 2 list
    numinrange = -4 + 8*numasint/maxnum # CHANGED TO OUR VALUES
    # print(numinrange)
    return numinrange
示例#3
0
    def fitness_ras(self, pop):
        xdim = self.length // self.dim
        fVals = []
        fObj = []
        for i in range(len(pop)):
            #xGC=[''.join(pop[i])[j*xdim:(j+1)*xdim] for j in range(0,self.dim)]
            #print(xdim)
            self.xGC = [
                gray_to_bin(''.join(pop[i]))[(j * xdim):((j + 1) * xdim)]
                for j in range(0, self.dim)
            ]
            #print(pop)
            #self.xGC=[(''.join(pop[i]))[(j*xdim):((j+1)*xdim)] for j in range(0,self.dim)]

            #print(self.xGC)
            x = [int(i, 2) / 8192. - 4. for i in self.xGC]
            rhs = [m**2. - 10. * np.cos(2. * np.pi * m) for m in x]
            f_x = 10. * self.dim + sum(rhs)
            fVals.append(f_x)
            fObj.append(self.BigConst - f_x)

            #print(xGC)
            #print(x)
            #print(f_x)
            #wait = input("PRESS ENTER TO CONTINUE.")

        return fVals[:], fObj[:]
示例#4
0
 def __init__(self, chromosome):
     self.chromosome = chromosome
     xd = gray_to_bin(self.chromosome)
     xd = int(xd, 2)
     h = 10 / (2 ** 20)
     start = -5
     self.x = start + h * xd
     self.fc = self.function_c()
     self.fp = self.function_c(p=True)
示例#5
0
def plot_some(population, ax, start=-5, h=10 / (2 ** 20)):
    xn = []
    for elem in population:
        x = int(gray_to_bin(elem.chromosome), 2)
        x = start + h * x
        xn.append(x)
    y1 = ygr(xn)
    ax.scatter(xn, y1, color='red')
    ax.grid()
 def mutation(self):
     for i in range(self.pop_size):
         for j in range(self.n_var):
             for k in range(self.bits_per_variable):
                 r = random.random()
                 if r <= self.mutation_rate:
                     gray_code_son = gc.bin_to_gray(self.sons[i].binary_code[j])
                     if gray_code_son[k] == '1':
                         gray_code_son = list(gray_code_son)
                         gray_code_son[k] = '0'
                         gray_code_son = ''.join(gray_code_son)
                     else:
                         gray_code_son = list(gray_code_son)
                         gray_code_son[k] = '1'
                         gray_code_son = ''.join(gray_code_son)
                     self.sons[i].binary_code[j] = gc.gray_to_bin(gray_code_son)
示例#7
0
def decode(f, dim=None, coding=None):
    if dim == None:
        dim = parameters.ndim
    if coding == None:
        coding = parameters.coding

    if dim > 1:
        if isinstance(f, str):
            f = [f[i:i + 62] for i in range(dim)]
    if coding == 'bin':
        return bin_to_double(f)
    elif coding == 'gray':
        # return bin_to_gray(double_to_bin(f))
        return bin_to_double(gray_to_bin(f))
    else:
        raise ValueError("Unknown number coding {}".format(coding))
示例#8
0
def gray_str_to_binary_str(gray_str):
    binary_str = []
    for i in np.arange(len(gray_str)):
        binary_str.append(gray_to_bin(gray_str[i]))
    return binary_str
示例#9
0
 def grayToBinary(self,gray):
     return int( gray_to_bin( bin(gray)[2:] ),2 )
def gray_to_uint(code):
    return Bits(bin=gray_to_bin(code)).uint
def chrom2real(c):
    indasstring=''.join(map(str, c))
    degray=gray_to_bin(indasstring)
    numasint=int(degray, 2) # convert to int from base 2 list
    numinrange=-5+10*numasint/maxnum
    return numinrange
示例#12
0
def test_live_issue_117():
    assert bin_to_gray('0100') == '0110'
    assert bin_to_gray('0101') == '0111'
    for bits in ('0100', '0101'):
        assert gray_to_bin(bin_to_gray(bits)) == bits
示例#13
0
def test_live_issue_117():
    assert bin_to_gray('0100') == '0110'
    assert bin_to_gray('0101') == '0111'
    for bits in ('0100', '0101'):
        assert gray_to_bin(bin_to_gray(bits)) == bits
示例#14
0
def test_live_issue_117():
    assert bin_to_gray("0100") == "0110"
    assert bin_to_gray("0101") == "0111"
    for bits in ("0100", "0101"):
        assert gray_to_bin(bin_to_gray(bits)) == bits
示例#15
0
    def runMain(self):
        self.old_pop = self.pop[:]
        self.new_pop = self.fitnessFun(self.old_pop)

        if self.problem == 'maxone':
            self.bestChromosome.append(max(self.fitnessVals))
            mem = self.new_pop[np.where(
                np.asarray(self.fitnessVals) == max(self.fitnessVals))[0][0]]
            self.bestChromosomeBin.append(''.join(mem))

        if self.problem == 'ras':
            self.bestChromosome.append(min(self.fitnessVals))
            mem = self.new_pop[np.where(
                np.asarray(self.fitnessVals) == max(self.fitnessVals))[0][0]]
            self.bestChromosomeBin.append(gray_to_bin(''.join(mem)))

        if self.eC > 0:
            ind = rnd.randint(0, self.popSize)
            self.new_pop[ind:ind + self.eC] = self.elPop(
                self.old_pop, self.fitnessVals)

        cnt = 0
        while True:
            #            self.new_pop=self.fitnessFun(self.old_pop)
            #           self.bestChromosome.append(max(self.fitnessVals))
            cnt = cnt + 1
            #            print(cnt)
            self.fitAll.append(self.fitnessVals)
            if self.problem == 'maxone' or self.problem == 'ras':
                if cnt == self.maxGen:  #or max(self.fitnessVals)==self.length:
                    break

            crosMates = [(i, i + 1) for i in range(0, self.popSize, 2)]
            for i in range(len(crosMates)):
                m = crosMates[i][0]
                p = crosMates[i][1]
                self.new_pop[m], self.new_pop[p] = self.crossover(
                    self.new_pop[m], self.new_pop[p])

            for i in range(0, self.popSize):
                self.new_pop[i] = self.mutate(self.new_pop[i])

            self.old_pop = self.new_pop[:]
            self.new_pop = self.fitnessFun(self.new_pop)

            #if self.problem == 'maxone':
            #    self.fitnessVals = [len(list(filter(lambda x: x=='1', self.new_pop[x]))) for x in range(0,self.popSize)]
            #          if self.problem == 'ras':

            if self.eC > 0:
                ind = rnd.randint(0, self.popSize)
                self.new_pop[ind:ind + self.eC] = self.elPop(
                    self.new_pop, self.fitnessVals)
            if self.problem == 'maxone':
                self.bestChromosome.append(max(self.fitnessVals))
                mem = self.new_pop[np.where(
                    np.asarray(self.fitnessVals) == max(self.fitnessVals))[0]
                                   [0]]
                self.bestChromosomeBin.append(''.join(mem))
            if self.problem == 'ras':
                self.bestChromosome.append(min(self.fitnessVals))
                mem = self.new_pop[np.where(
                    np.asarray(self.fitnessVals) == min(self.fitnessVals))[0]
                                   [0]]
                #self.bestChromosomeBin.append(''.join(mem))
                self.bestChromosomeBin.append(gray_to_bin(''.join(mem)))