Esempio n. 1
0
def run_p1(input_sring,TIME=30,GENERATION_SIZE=10,GENERATION_REMOVE=1):
    # GENERATION_SIZE = 4
    # GENERATION_REMOVE = 1
    # MAX_GENERATION = 30



    response = readcsv(input_sring)
    # print response
    goal = response.pop(0)
    # print goal,response

    f_gen = first_gen(response,GENERATION_SIZE, goal)
    # print f_gen

    best_pop = None
    future_gen = []
    future_gen.extend(f_gen)

    tstart = time()
    DIFF = time() - tstart
    NUM_GEN = 0
    while (DIFF) < TIME:
        NUM_GEN = NUM_GEN + 1
        future_gen = eval_pop(future_gen,goal)
        # print("Your future gen is: ",future_gen)

        num_picked = GENERATION_SIZE-GENERATION_REMOVE              ## Get the number of populations to take
        future_gen = pickPeople(future_gen, num_picked)             ## Set the genration to the 'num_picked' populations, with the removed pop replaced with the top pop
        # print ("Your You picked: ",future_gen)

        future_gen = crossover(future_gen, None)
        # print("Your crossover gen is: ",future_gen)

        future_gen = mutation(future_gen, response, goal, 0)
        # print ("Your mutated gen is: ",future_gen)

        future_gen = eval_pop(future_gen,goal)
        # print ("Your Re-Evaluated gen is: ",future_gen)

        best_pop,index = getBestPop(future_gen)
        if best_pop.getRatings() == 100:
            DIFF = time() - tstart
            break
        DIFF = time() - tstart

    print "You have finished, here is your population: "
    print best_pop
    print "It took "+str(NUM_GEN)+ " generations."
    print "And required "+str(DIFF)+" seconds."
Esempio n. 2
0
def evolution(ersteGeneration, ziel, abc, selecGewicht=[1.0, 1.0, 1.0], mutaAnteil=0.1):
    neueGen = ersteGeneration
    laufIndex = 0.0
    while True:
        tempSelec = selektion(neueGen, ziel, selecGewicht)
        tempGen = crossover(tempSelec, len(ersteGeneration))
        neueGen = mutation(tempGen, abc, mutaAnteil)
        laufIndex += 1
        print laufIndex
        if laufIndex > 1000000:
            print "Ueberlauf!!"
            break
        if neueGen[0] == ziel:
            return laufIndex
Esempio n. 3
0
    def children_production(self, crossover_number, parents):
        """
        Takes randomly 2 parents in the parents list and makes them crossover to give a child
        Note: the crossover method is contained in self.crossover_method

        :param crossover_number:(int) Number of children needed
        :param parents:(list of NeuralNetwork) Potential parents
        :return:(list of NeuralNetwork) Children

        Todo: Use pseudo parallelization to speed up
        """
        children = []
        for i in range(crossover_number):
            child = crossover(self.env, parents[randint(0, crossover_number - 1)],
                              parents[randint(0, crossover_number - 1)], self.crossover_method)
            children.append(child)
        return children
Esempio n. 4
0
def MODE(nIter, nChr, nPop, F, Cr, func, lb, rb):
    """多目标差分进化算法主程序 
    Params:
        nIter: 迭代次数
        nPop: 种群规模 
        F: 缩放因子 
        Cr: 交叉概率 
        func:优化函数 
        lb: 自变量下界 
        rb:自变量上界 
    Return:
        paretoPops: 帕累托解集 
        paretoFits: 对应的适应度 
    """
    # 生成初始种群
    parPops = initPop(nChr, nPop, lb, rb)
    parFits = fitness(parPops, func)

    # 开始迭代
    iter = 1
    while iter <= nIter:
        # 进度条
        print("【进度】【{0:20s}】【正在进行{1}代...】【共{2}代】".\
            format('▋'*int(iter/nIter*20), iter, nIter), end='\r')

        mutantPops = mutate(parPops, F, lb, rb)  # 产生变异向量
        trialPops = crossover(parPops, mutantPops, Cr)  # 产生实验向量
        trialFits = fitness(trialPops, func)  # 重新计算适应度

        pops = np.concatenate((parPops, trialPops), axis=0)  # 合并成新的种群
        fits = np.concatenate((parFits, trialFits), axis=0)
        ranks = nonDominationSort(pops, fits)  # 非支配排序
        distances = crowdingDistanceSort(pops, fits, ranks)  # 计算拥挤度

        parPops, parFits = select1(nPop, pops, fits, ranks, distances)

        iter += 1
    print("\n")
    # 获取等级为0,即实际求解得到的帕累托前沿
    paretoPops = pops[ranks == 0]
    paretoFits = fits[ranks == 0]

    return paretoPops, paretoFits
Esempio n. 5
0
def NSGA2(nIter, nChr, nPop, pc, pm, etaC, etaM, func, lb, rb):
    """非支配遗传算法主程序 
    Params:
        nIter: 迭代次数 
        nPop: 种群大小 
        pc: 交叉概率 
        pm: 变异概率 
        func: 优化的函数 
        lb: 自变量下界
        rb: 自变量上界 
    """
    # 生成初始种群
    pops = initPops(nPop, nChr, lb, rb)
    fits = fitness(pops, func)

    # 开始第1次迭代
    iter = 1
    while iter <= nIter:
        # 进度条
        print("【进度】【{0:20s}】【正在进行{1}代...】【共{2}代】".\
            format('▋'*int(iter/nIter*20), iter, nIter), end='\r')
        ranks = nonDominationSort(pops, fits)  # 非支配排序
        distances = crowdingDistanceSort(pops, fits, ranks)  # 拥挤度
        pops, fits = select1(nPop, pops, fits, ranks, distances)
        chrpops = crossover(pops, pc, etaC, lb, rb)  # 交叉产生子种群
        chrpops = mutate(chrpops, pm, etaM, lb, rb)  # 变异产生子种群
        chrfits = fitness(chrpops, func)
        # 从原始种群和子种群中筛选
        pops, fits = optSelect(pops, fits, chrpops, chrfits)
        iter += 1
    # 对最后一代进行非支配排序
    ranks = nonDominationSort(pops, fits)  # 非支配排序
    distances = crowdingDistanceSort(pops, fits, ranks)  # 拥挤度
    paretoPops = pops[ranks == 0]
    paretoFits = fits[ranks == 0]
    return paretoPops, paretoFits
Esempio n. 6
0
 def select(self, indi):
     '''
     select
         indi = current indi id
         
     1. determine the type of selection the user requested
     2. call the requested method
     3. use the winner to call crossover
     '''
     num_rounds = 2
     k = 2
     winner = [] # id of winner returned by tournament
     # need to make sure num_rounds is an even number
     for i in range(0, num_rounds):
         winner += [self.tournament(k, indi)]
     
     # call crossover on winner        
     child_id = crossover().crossover(random.choice(winner), random.choice(winner), 1)   # returns id of child that was just created
     
     # mutate
     #mutate().mutate(random.choice(winner))
     self.mutate(child_id)
     
     raise web.seeother('/fitness/' + str(int(indi) + 1))
Esempio n. 7
0
def main():
    """ PROJECT 02 """
    N = 10  # population size
    Pc = 0.8  # probability crossover
    Pm = 0.1  # probability mutation
    sigma = 1  # strength of mutation
    maxGenerations = 30  # number of generations

    alpha = 0.75  # crossoverArithmetic()         Alg Parameter
    percentile = 50  # selectionTruncate()           Alg Parameter
    k = 2  # selectionTournament() k       Alg Parameter
    P = 0.40  # selectionTournament() P       Alg Parameter

    listBOR = list()
    listAVG = list()
    listSTD = list()
    #1
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], sigma)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], sigma)
    print(f'\tSimulation 1:')
    printChromosome(chrm01)

    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionTournament(chrm01, k, P)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverShuffle(chrm01[gene],
                                                 chrm01[gene + 1])
                    chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                    chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
        fitness.append(getFitness(chrm01))
        minFit = float("inf")
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Tournament Selection, Shuffle Crossover, Random Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])
    #2
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 2:')
    printChromosome(chrm01)

    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionTournament(chrm01, k, P)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverUniform(chrm01[gene],
                                                 chrm01[gene + 1])
                    chrm01[gene] = mutateGaussian(tempTuple[0], Pm, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], Pm, sigma)
        fitness.append(getFitness(chrm01))
        minFit = 1000
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Tournament Selection, 1-Point Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #3
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionTournament(chrm01, k, P)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 3:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionProportional(chrm01, N)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                    chrm01[gene] = mutateGaussian(tempTuple[0], Pm, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], Pm, sigma)
        fitness.append(getFitness(chrm01))
        minFit = 1000
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Tournament Selection, 1-Point Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #4
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 4:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionProportional(chrm01, N)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                    chrm01[gene] = mutateGaussian(tempTuple[0], Pm, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], Pm, sigma)
        fitness.append(getFitness(chrm01))
        minFit = float("inf")
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Proportional Selection, 1-Point Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #5
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 5:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionTruncate(chrm01, percentile)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverArithmetic(chrm01[gene],
                                                    chrm01[gene + 1], alpha)
                    chrm01[gene] = mutateGaussian(tempTuple[0], Pm, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], Pm, sigma)
        fitness.append(getFitness(chrm01))
        minFit = float("inf")
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Truncate Selection, Arithmetic Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #6
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 6:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionRankingFitness(chrm01)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverShuffle(chrm01[gene],
                                                 chrm01[gene + 1])
                    chrm01[gene] = mutateRandom(tempTuple[0], .10)
                    chrm01[gene + 1] = mutateRandom(tempTuple[1], .10)
        fitness.append(getFitness(chrm01))
        minFit = 1000
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Ranking Selection, Shuffle Crossover, Random Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #7
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 7:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionRankingFitness(chrm01)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                    chrm01[gene] = mutateGaussian(tempTuple[0], .10, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], .10, sigma)
        fitness.append(getFitness(chrm01))
        minFit = float("inf")
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Ranking Selection, 1-Point Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #8
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 8:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionTournament(chrm01, 3, P)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverShuffle(chrm01[gene],
                                                 chrm01[gene + 1])
                    chrm01[gene] = mutateGaussian(tempTuple[0], .10, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], .10, sigma)
        fitness.append(getFitness(chrm01))
        minFit = 1000
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Tournament(3) Selection, Shuffle Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #9
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], Pm)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], Pm)
    print(f'\tSimulation 9:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionTournament(chrm01, 5, P)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverArithmetic(chrm01[gene],
                                                    chrm01[gene + 1], alpha)
                    chrm01[gene] = mutateGaussian(tempTuple[0], .10, sigma)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], .10, sigma)
        fitness.append(getFitness(chrm01))
        minFit = float("inf")
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Tournament(5) Selection, Arithmetic Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    #10
    # init first generation
    chrm01 = initChromosome(N, 3)
    chrm01 = selectionSimple(chrm01, 10)  # 1:1 resample
    for gene in range(0, len(chrm01)):
        if (gene % 2 == 0):
            if (random.uniform(1, 10) <= (Pc * 10)):
                tempTuple = crossover(chrm01[gene], chrm01[gene + 1])
                chrm01[gene] = mutateRandom(tempTuple[0], .5)
                chrm01[gene + 1] = mutateRandom(tempTuple[1], .5)
    print(f'\tSimulation 10:')
    printChromosome(chrm01)
    fitness = list()
    avgList = list()
    for i in range(0, maxGenerations):
        "Do 30 runs"
        selectionTruncate(chrm01, percentile)
        for gene in range(0, len(chrm01)):
            if (gene % 2 == 0):
                if (random.uniform(1, 10) <= (Pc * 10)):
                    tempTuple = crossoverUniform(chrm01[gene],
                                                 chrm01[gene + 1])
                    chrm01[gene] = mutateGaussian(tempTuple[0], Pm, .3)
                    chrm01[gene + 1] = mutateGaussian(tempTuple[1], Pm, .3)
        fitness.append(getFitness(chrm01))
        minFit = float("inf")
        maxFit = 0
        for stat in fitness:
            if abs(stat[0]) < minFit:
                minFit = stat[0]
                if abs(stat[1]) > maxFit:
                    maxFit = stat[1]
                avgList.append(stat[2])
    print(
        "\tResults after 30 generations with Truncate Selection, Uniform Crossover, Gaussian Mutation:"
    )
    print(
        f'\tFitness \'Best in run\' : {minFit}\n\tFitness \'Worst in Run\' : {maxFit}\n\tFitness Average (overall) : {mean(avgList)}\n'
    )
    listBOR.append(minFit)
    listAVG.append(mean(avgList))
    listSTD.append(getFitness(chrm01)[3])

    print(
        "---> After 10 simulations of different configurations (each sim with 30 generations)"
    )
    print(
        f'\tBest of all runs: {min(listBOR, key=abs)} | stdev: {stdev(listBOR)}\n\tAverage of all best of runs: {mean(listBOR)} | stdev: {stdev(listBOR)}\n\tAverage of all run averages: {mean(listAVG)} | stdev: {stdev(listAVG)}\n'
    )

    t = PrettyTable([
        'Simulation #', 'Best of 30 Runs', 'Average of 30 BORs',
        'Standard Deviation of 30 BORs'
    ])
    for i in range(0, 10):
        t.add_row(
            [f'{i+1}', f'{listBOR[i]}', f'{listAVG[i]}', f'{listSTD[i]}'])
    print(t)
Esempio n. 8
0
solution = [0] * 10000000
max_val = (2**(globals.no_of_labels)) - 1
fitness_val = 100000000
#print('max val ={}'.format(max_val))
b = random.randrange(1, max_val)
for i in range(0, globals.no_of_iterations):
    a = random.randrange(1, max_val)
    #print("values of a and b are {} {}".format(a,b))
    a = binary(a, globals.no_of_labels)
    b = binary(b, globals.no_of_labels)
    #print(a,b)
    a = str(a)
    b = str(b)
    #print(a,b)
    s = crossover(globals.graph, a, b)
    s = str(encode(s))
    """print("encode s {}".format(s))
  print("devesh")
  print(s)
  print("mut starts")"""
    #print("after crossover {}".format(s))
    t = mutation(globals.graph, s)
    """print("after mutation {}".format(t))
  print("mut ends")"""
    x = fitness(t)
    s2 = t
    if len(solution) > len(s2):
        solution = s2
        fitness_val = len(s2)
        b = s2
Esempio n. 9
0
def geneticAlgorithm(userID):
    #Αρχικοποίηση πληθυσμού του χρήστη και εύρεση 10 πιο κοντινών γειτόνων
    initPop = initialPopulationFull(userID)
    tenSimilar = pearsonbyuser(userID)
    print("User", userID, "'s most similar users are:", tenSimilar)

    #Είσοδος του μεγέθους αρχικού πληθυσμού και επιλογή αρχικού πληθυσμού με τη μέθοδο ρουλέτας με βάση το κόστος
    size = int(input("Size of Initial Population: "))
    initialPopulationUser = initialPopulation(userID, size)
    selectedMoviesbyUser = initialPopulationUser[0]
    initialPopulationChromosomes = initialPopulationUser[1]
    userSum = 0
    for x in range(len(initialPopulationUser[1])):
        userSum = userSum + initialPopulationUser[1][x]
    userMean = userSum / len(initialPopulationUser[1])
    #Εμφάνιση επιλεγμένων ταινιών και αρχικών χρωμοσωμάτων
    if size < 50:
        try:
            selectedMovieNames = []
            for x in selectedMoviesbyUser:
                selectedMovieNames.append(movieNameById(x))
            print("User no:", userID,
                  "selected movies as chromosomes names are",
                  selectedMovieNames)
        except:
            print("Can't display movie names")
    #print("User no:",userID,"initial population chromosomes are",initialPopulationChromosomes)
    #Ορισμός Mating Pool
    matingPool = []
    for x in range(len(tenSimilar)):
        matingPool.append(
            userPopulationBySelectedMovies(tenSimilar[x],
                                           selectedMoviesbyUser))
    #print(matingPool)

    generationNum = int(input("Number of Generations "))
    #Εύρεση Καταλληλότερου συζυγούς γονεά για τον χρήστη userID
    fittestParentGA = fitnessFunction(initialPopulationChromosomes, matingPool,
                                      userMean)
    generationList = []
    generationFittness = []
    fitnessParentOverallList = []
    for x in range(generationNum):
        #Χρησιμοποιείται ελιτισμός, αφού με κάθε νέα γενιά, αντικαθίσταται το χρωμόσωμα με τον καλύτερο πιθανό γονέα από το mating pool
        effectCoeff = random.randint(1, 100)
        elitismCoeff = 100
        crossoverCoeff = 100
        if elitismCoeff >= effectCoeff:
            fittestParentGA = fitnessFunction(initialPopulationChromosomes,
                                              matingPool, userMean)
            print("elitism")
        if crossoverCoeff >= effectCoeff:
            crossover(initialPopulationChromosomes,
                      matingPool[fittestParentGA[0]])
        generationList.append(x)
        generationFittness.append(fittestParentGA[1])
        print("Generation: ", x + 1, "Generation Fitness", fittestParentGA[1])
        fitnessParentOverallList.append(tenSimilar[fittestParentGA[0]])
    uniquefitnessParentOverallList = []
    for x in fitnessParentOverallList:
        if x not in uniquefitnessParentOverallList:
            uniquefitnessParentOverallList.append(x)
    for x in range(len(uniquefitnessParentOverallList)):
        findMoviesToPropose(userID, uniquefitnessParentOverallList[x])
    plt.plot(generationList, generationFittness)
    plt.show()
## These initial timeTableSchedules are populated in the globalScheduleMap 

generateRandomTimeTableSchedules()

## Now we have to sort the globalScheduleMap on value i.e fitness.
## But as a map has no order inherently, it would be a wise decision
## to get a sorted list of tuples of the form [(timeTableSchedule,fitness)],
## where the elements of the list are sorted on the fitness value

sortedGlobalScheduleMapList=sorted(globalScheduleMap.iteritems(),key=operator.itemgetter(1),reverse=True)

while(sortedGlobalScheduleMapList[0][1]<=requiredFitness):
		## Now perform crossover of first numInitialSelectedSchedules pairs of schedules and store them in a list 
		newTimeTablesList=[]
		for i in range(numInitialSelectedSchedules):
			newTimeTablesList+=[crossover(sortedGlobalScheduleMapList[2*i][0],sortedGlobalScheduleMapList[2*i+1][0])]
			
		## Perform mutation of the generated Time Tables
		for i in range(len(newTimeTablesList)):
			newTimeTablesList[i]=mutate(newTimeTablesList[i])

		## Check if the mutated time tables finess is better than the timetable with least fitness in the sortedGlobalScheduleMapList
		## If so replace that time table in the globalScheduleMap with the current map
		## else skip the current map
		for i in range (len(newTimeTablesList)):
			curFitness=fitness(newTimeTablesList[i])
			if curFitness>sortedGlobalScheduleMapList[len(sortedGlobalScheduleMapList)-1][1]):
				globalScheduleMap.pop(sortedGlobalScheduleMapList[len(sortedGlobalScheduleMapList)-1][0])
				globalScheduleMap[newTimeTablesList[i]]=curFitness
				## Update the sortedGlobalScheduleMapList as the globalScheduleMap is updated
				sortedGlobalScheduleMapList=sorted(globalScheduleMap.iteritems(),key=operator.itemgetter(1),reverse=True)
Esempio n. 11
0
    def __init__(self,
                 f,
                 x0,
                 ranges=[],
                 fmt='f',
                 fitness=Fitness,
                 selection=RouletteWheel,
                 crossover=TwoPoint,
                 mutation=BitToBit,
                 elitist=True):
        '''
        Initializes the population and the algorithm.

        On the initialization of the population, a lot of parameters can be set.
        Those will deeply affect the results. The parameters are:

        :Parameters:
          f
            A multivariable function to be evaluated. The nature of the
            parameters in the objective function will depend of the way you want
            the genetic algorithm to process. It can be a standard function that
            receives a one-dimensional array of values and computes the value of
            the function. In this case, the values will be passed as a tuple,
            instead of an array. This is so that integer, floats and other types
            of values can be passed and processed. In this case, the values will
            depend of the format string (see below)

            If you don't supply a format, your objective function will receive a
            ``Chromosome`` instance, and it is the responsability of the
            function to decode the array of bits in any way. Notice that, while
            it is more flexible, it is certainly more difficult to deal with.
            Your function should process the bits and compute the return value
            which, in any case, should be a scalar.

            Please, note that genetic algorithms maximize functions, so project
            your objective function accordingly. If you want to minimize a
            function, return its negated value.

          x0
            A population of first estimates. This is a list, array or tuple of
            one-dimension arrays, each one corresponding to an estimate of the
            position of the minimum. The population size of the algorithm will
            be the same as the number of estimates in this list. Each component
            of the vectors in this list are one of the variables in the function
            to be optimized.

          ranges
            Since messing with the bits can change substantially the values
            obtained can diverge a lot from the maximum point. To avoid this,
            you can specify a range for each of the variables. ``range``
            defaults to ``[ ]``, this means that no range checkin will be done.
            If given, then every variable will be checked. There are two ways to
            specify the ranges.

            It might be a tuple of two values, ``(x0, x1)``, where ``x0`` is the
            start of the interval, and ``x1`` its end. Obviously, ``x0`` should
            be smaller than ``x1``. If ``range`` is given in this way, then this
            range will be used for every variable.

            It can be specified as a list of tuples with the same format as
            given above. In that case, the list must have one range for every
            variable specified in the format and the ranges must appear in the
            same order as there. That is, every variable must have a range
            associated to it.

          fmt
            A ``struct``-format string. The ``struct`` module is a standard
            Python module that packs and unpacks informations in bits. These
            are used to inform the algorithm what types of data are to be used.
            For example, if you are maximizing a function of three real
            variables, the format should be something like ``"fff"``. Any type
            supported by the ``struct`` module can be used. The GA will decode
            the bit array according to this format and send it as is to your 
            fitness function -- your function *must* know what to do with them.

            Alternatively, the format can be an integer. In that case, the GA
            will not try to decode the bit sequence. Instead, the bits are
            passed without modification to the objective function, which must
            deal with them. Notice that, if this is used this way, the
            ``ranges`` property (see below) makes no sense, so it is set to
            ``None``. Also, no sanity checks will be performed.

            It defaults to `"f"`, that is, a single floating point variable.

          fitness
            A fitness method to be applied over the objective function. This
            parameter must be a ``Fitness`` instance or subclass. It will be
            applied over the objective function to compute the fitness of every
            individual in the population. Please, see the documentation on the
            ``Fitness`` class.

          selection
            This specifies the selection method. You can use one given in the
            ``selection`` sub-module, or you can implement your own. In any
            case, the ``selection`` parameter must be an instance of
            ``Selection`` or of a subclass. Please, see the documentation on the
            ``selection`` module for more information. Defaults to
            ``RouletteWheel``. If made ``None``, then selection will not be
            present in the GA.

          crossover
            This specifies the crossover method. You can use one given in the
            ``crossover`` sub-module, or you can implement your own. In any
            case, the ``crossover`` parameter must be an instance of
            ``Crossover`` or of a subclass. Please, see the documentation on the
            ``crossover`` module for more information. Defaults to
            ``TwoPoint``. If made ``None``, then crossover will not be
            present in the GA.

          mutation
            This specifies the mutation method. You can use one given in the
            ``mutation`` sub-module, or you can implement your own. In any
            case, the ``mutation`` parameter must be an instance of ``Mutation``
            or of a subclass. Please, see the documentation on the ``mutation``
            module for more information. Defaults to ``BitToBit``.  If made
            ``None``, then mutation will not be present in the GA.

          elitist
            Defines if the population is elitist or not. An elitist population
            will never discard the fittest individual when a new generation is
            computed. Defaults to ``True``.
        '''
        list.__init__(self, [])
        self.__fx = []
        for x in x0:
            x = array(x).ravel()
            c = Chromosome(fmt)
            c.encode(tuple(x))
            self.append(c)
            self.__fx.append(f(x))
        self.__f = f
        self.__csize = self[0].size
        self.elitist = elitist
        '''If ``True``, then the population is elitist.'''

        if type(fmt) == int:
            self.ranges = None
        elif ranges is None:
            self.ranges = zip(amin(self, axis=0), amax(self, axis=1))
        else:
            ranges = list(ranges)
            if len(ranges) == 1:
                self.ranges = array(ranges * len(x0[0]))
            else:
                self.ranges = array(ranges)
                '''Holds the ranges for every variable. Although it is a
                writable property, care should be taken in changing parameters
                before ending the convergence.'''

        # Sanitizes the first estimate. It is not expected that the values
        # received as first estimates are outside the ranges, but a check is
        # made anyway. If any estimate is outside the bounds, a new random
        # vector is choosen.
        if self.ranges is not None: self.sanity()

        # Verifies the validity of the fitness method
        try:
            issubclass(fitness, Fitness)
            fitness = fitness()
        except TypeError:
            pass
        if not isinstance(fitness, Fitness):
            raise TypeError, 'not a valid fitness function'
        else:
            self.__fit = fitness
        self.__fitness = self.__fit(self.__fx)

        # Verifies the validity of the selection method
        try:
            issubclass(selection, Selection)
            selection = selection()
        except TypeError:
            pass
        if not isinstance(selection, Selection):
            raise TypeError, 'not a valid selection method'
        else:
            self.__select = selection

        # Verifies the validity of the crossover method
        try:
            issubclass(crossover, Crossover)
            crossover = crossover()
        except TypeError:
            pass
        if not isinstance(crossover, Crossover) and crossover is not None:
            raise TypeError, 'not a valid crossover method'
        else:
            self.__crossover = crossover

        # Verifies the validity of the mutation method
        try:
            issubclass(mutation, Mutation)
            mutation = mutation()
        except TypeError:
            pass
        if not isinstance(mutation, Mutation) and mutation is not None:
            raise TypeError, 'not a valid mutation method'
        else:
            self.__mutate = mutation
Esempio n. 12
0
    def __init__(self, fitness, fmt, ranges=[ ], size=50,
                 selection=RouletteWheel, crossover=TwoPoint,
                 mutation=BitToBit, elitist=True):
        '''
        Initializes the population and the algorithm.

        On the initialization of the population, a lot of parameters can be set.
        Those will deeply affect the results. The parameters are:

        :Parameters:
          fitness
            A fitness function to serve as an objective function. In general, a
            GA is used for maximizing a function. This parameter can be a
            standard Python function or a ``Fitness`` instance.

            In the first case, the GA will convert the function in a
            ``Fitness`` instance and call it internally when needed. The
            function should receive a tuple or vector of data according to the
            given ``Chromosome`` format (see below) and return a numeric value.

            In the second case, you can use any of the fitness methods of the
            ``fitness`` sub-module, or create your own. If you want to use your
            own fitness method (for experimentation or simulation, for example),
            it must be an instance of a ``Fitness`` or of a subclass, or an
            exception will be raised. Please consult the documentation on the
            ``fitness`` sub-module.

          fmt
            A ``struct``-format string. The ``struct`` module is a standard
            Python module that packs and unpacks informations in bits. These
            are used to inform the algorithm what types of data are to be used.
            For example, if you are maximizing a function of three real
            variables, the format should be something like ``"fff"``. Any type
            supported by the ``struct`` module can be used. The GA will decode
            the bit array according to this format and send it as is to your 
            fitness function -- your function *must* know what to do with them.

            Alternatively, the format can be an integer. In that case, the GA
            will not try to decode the bit sequence. Instead, the bits are
            passed without modification to the objective function, which must
            deal with them. Notice that, if this is used this way, the
            ``ranges`` property (see below) makes no sense, so it is set to
            ``None``. Also, no sanity checks will be performed.

          ranges
            Since messing with the bits can change substantially the values
            obtained can diverge a lot from the maximum point. To avoid this,
            you can specify a range for each of the variables. ``range``
            defaults to ``[ ]``, this means that no range checkin will be done.
            If given, then every variable will be checked. There are two ways to
            specify the ranges.

            It might be a tuple of two values, ``(x0, x1)``, where ``x0`` is the
            start of the interval, and ``x1`` its end. Obviously, ``x0`` should
            be smaller than ``x1``. If ``range`` is given in this way, then this
            range will be used for every variable.

            If can be specified as a list of tuples with the same format as
            given above. In that case, the list must have one range for every
            variable specified in the format and the ranges must appear in the
            same order as there. That is, every variable must have a range
            associated to it.

          size
            This is the size of the population. It defaults to 50.

          selection
            This specifies the selection method. You can use one given in the
            ``selection`` sub-module, or you can implement your own. In any
            case, the ``selection`` parameter must be an instance of
            ``Selection`` or of a subclass. Please, see the documentation on the
            ``selection`` module for more information. Defaults to
            ``RouletteWheel``. If made ``None``, then selection will not be
            present in the GA.

          crossover
            This specifies the crossover method. You can use one given in the
            ``crossover`` sub-module, or you can implement your own. In any
            case, the ``crossover`` parameter must be an instance of
            ``Crossover`` or of a subclass. Please, see the documentation on the
            ``crossover`` module for more information. Defaults to
            ``TwoPoint``. If made ``None``, then crossover will not be
            present in the GA.

          mutation
            This specifies the mutation method. You can use one given in the
            ``mutation`` sub-module, or you can implement your own. In any
            case, the ``mutation`` parameter must be an instance of ``Mutation``
            or of a subclass. Please, see the documentation on the ``mutation``
            module for more information. Defaults to ``BitToBit``.  If made
            ``None``, then mutation will not be present in the GA.

          elitist
            Defines if the population is elitist or not. An elitist population
            will never discard the fittest individual when a new generation is
            computed. Defaults to ``True``.
        '''
        list.__init__(self, [ ])
        for i in xrange(size):
            self.append(Chromosome(fmt))
        if self[0].format is None:
            self.__nargs = 1
            self.ranges = None
        else:
            self.__nargs = len(self[0].decode())
            if not ranges:
                self.ranges = None
            elif len(ranges) == 1:
                self.ranges = array(ranges * self.__nargs)
            else:
                self.ranges = array(ranges)
                '''Holds the ranges for every variable. Although it is a writable
                property, care should be taken in changing parameters before ending
                the convergence.'''
        self.__csize = self[0].size
        self.elitist = elitist
        '''If ``True``, then the population is elitist.'''
        self.fitness = zeros((len(self),), dtype=float)
        '''Vector containing the computed fitness value for every individual.'''

        # Sanitizes the generated values randomly created for the chromosomes.
        if self.ranges is not None: self.sanity()

        # Verifies the validity of the fitness method
        if isinstance(fitness, types.FunctionType):
            fitness = Fitness(fitness)
        if not isinstance(fitness, Fitness):
            raise TypeError, 'not a valid fitness function'
        else:
            self.__fit = fitness
        self.__fit(self)

        # Verifies the validity of the selection method
        try:
            issubclass(selection, Selection)
            selection = selection()
        except TypeError:
            pass
        if not isinstance(selection, Selection):
            raise TypeError, 'not a valid selection method'
        else:
            self.__select = selection

        # Verifies the validity of the crossover method
        try:
            issubclass(crossover, Crossover)
            crossover = crossover()
        except TypeError:
            pass
        if not isinstance(crossover, Crossover) and crossover is not None:
            raise TypeError, 'not a valid crossover method'
        else:
            self.__crossover = crossover

        # Verifies the validity of the mutation method
        try:
            issubclass(mutation, Mutation)
            mutation = mutation()
        except TypeError:
            pass
        if not isinstance(mutation, Mutation) and mutation is not None:
            raise TypeError, 'not a valid mutation method'
        else:
            self.__mutate = mutation
Esempio n. 13
0
    def __init__(self, f, x0, ranges=[ ], fmt='f', fitness=Fitness,
                 selection=RouletteWheel, crossover=TwoPoint,
                 mutation=BitToBit, elitist=True):
        '''
        Initializes the population and the algorithm.

        On the initialization of the population, a lot of parameters can be set.
        Those will deeply affect the results. The parameters are:

        :Parameters:
          f
            A multivariable function to be evaluated. The nature of the
            parameters in the objective function will depend of the way you want
            the genetic algorithm to process. It can be a standard function that
            receives a one-dimensional array of values and computes the value of
            the function. In this case, the values will be passed as a tuple,
            instead of an array. This is so that integer, floats and other types
            of values can be passed and processed. In this case, the values will
            depend of the format string (see below)

            If you don't supply a format, your objective function will receive a
            ``Chromosome`` instance, and it is the responsability of the
            function to decode the array of bits in any way. Notice that, while
            it is more flexible, it is certainly more difficult to deal with.
            Your function should process the bits and compute the return value
            which, in any case, should be a scalar.

            Please, note that genetic algorithms maximize functions, so project
            your objective function accordingly. If you want to minimize a
            function, return its negated value.

          x0
            A population of first estimates. This is a list, array or tuple of
            one-dimension arrays, each one corresponding to an estimate of the
            position of the minimum. The population size of the algorithm will
            be the same as the number of estimates in this list. Each component
            of the vectors in this list are one of the variables in the function
            to be optimized.

          ranges
            Since messing with the bits can change substantially the values
            obtained can diverge a lot from the maximum point. To avoid this,
            you can specify a range for each of the variables. ``range``
            defaults to ``[ ]``, this means that no range checkin will be done.
            If given, then every variable will be checked. There are two ways to
            specify the ranges.

            It might be a tuple of two values, ``(x0, x1)``, where ``x0`` is the
            start of the interval, and ``x1`` its end. Obviously, ``x0`` should
            be smaller than ``x1``. If ``range`` is given in this way, then this
            range will be used for every variable.

            It can be specified as a list of tuples with the same format as
            given above. In that case, the list must have one range for every
            variable specified in the format and the ranges must appear in the
            same order as there. That is, every variable must have a range
            associated to it.

          fmt
            A ``struct``-format string. The ``struct`` module is a standard
            Python module that packs and unpacks informations in bits. These
            are used to inform the algorithm what types of data are to be used.
            For example, if you are maximizing a function of three real
            variables, the format should be something like ``"fff"``. Any type
            supported by the ``struct`` module can be used. The GA will decode
            the bit array according to this format and send it as is to your 
            fitness function -- your function *must* know what to do with them.

            Alternatively, the format can be an integer. In that case, the GA
            will not try to decode the bit sequence. Instead, the bits are
            passed without modification to the objective function, which must
            deal with them. Notice that, if this is used this way, the
            ``ranges`` property (see below) makes no sense, so it is set to
            ``None``. Also, no sanity checks will be performed.

            It defaults to `"f"`, that is, a single floating point variable.

          fitness
            A fitness method to be applied over the objective function. This
            parameter must be a ``Fitness`` instance or subclass. It will be
            applied over the objective function to compute the fitness of every
            individual in the population. Please, see the documentation on the
            ``Fitness`` class.

          selection
            This specifies the selection method. You can use one given in the
            ``selection`` sub-module, or you can implement your own. In any
            case, the ``selection`` parameter must be an instance of
            ``Selection`` or of a subclass. Please, see the documentation on the
            ``selection`` module for more information. Defaults to
            ``RouletteWheel``. If made ``None``, then selection will not be
            present in the GA.

          crossover
            This specifies the crossover method. You can use one given in the
            ``crossover`` sub-module, or you can implement your own. In any
            case, the ``crossover`` parameter must be an instance of
            ``Crossover`` or of a subclass. Please, see the documentation on the
            ``crossover`` module for more information. Defaults to
            ``TwoPoint``. If made ``None``, then crossover will not be
            present in the GA.

          mutation
            This specifies the mutation method. You can use one given in the
            ``mutation`` sub-module, or you can implement your own. In any
            case, the ``mutation`` parameter must be an instance of ``Mutation``
            or of a subclass. Please, see the documentation on the ``mutation``
            module for more information. Defaults to ``BitToBit``.  If made
            ``None``, then mutation will not be present in the GA.

          elitist
            Defines if the population is elitist or not. An elitist population
            will never discard the fittest individual when a new generation is
            computed. Defaults to ``True``.
        '''
        list.__init__(self, [ ])
        self.__fx = [ ]
        for x in x0:
            x = array(x).ravel()
            c = Chromosome(fmt)
            c.encode(tuple(x))
            self.append(c)
            self.__fx.append(f(x))
        self.__f = f
        self.__csize = self[0].size
        self.elitist = elitist
        '''If ``True``, then the population is elitist.'''

        if type(fmt) == int:
            self.ranges = None
        elif ranges is None:
            self.ranges = zip(amin(self, axis=0), amax(self, axis=1))
        else:
            ranges = list(ranges)
            if len(ranges) == 1:
                self.ranges = array(ranges * len(x0[0]))
            else:
                self.ranges = array(ranges)
                '''Holds the ranges for every variable. Although it is a
                writable property, care should be taken in changing parameters
                before ending the convergence.'''

        # Sanitizes the first estimate. It is not expected that the values
        # received as first estimates are outside the ranges, but a check is
        # made anyway. If any estimate is outside the bounds, a new random
        # vector is choosen.
        if self.ranges is not None: self.sanity()

        # Verifies the validity of the fitness method
        try:
            issubclass(fitness, Fitness)
            fitness = fitness()
        except TypeError:
            pass
        if not isinstance(fitness, Fitness):
            raise TypeError, 'not a valid fitness function'
        else:
            self.__fit = fitness
        self.__fitness = self.__fit(self.__fx)

        # Verifies the validity of the selection method
        try:
            issubclass(selection, Selection)
            selection = selection()
        except TypeError:
            pass
        if not isinstance(selection, Selection):
            raise TypeError, 'not a valid selection method'
        else:
            self.__select = selection

        # Verifies the validity of the crossover method
        try:
            issubclass(crossover, Crossover)
            crossover = crossover()
        except TypeError:
            pass
        if not isinstance(crossover, Crossover) and crossover is not None:
            raise TypeError, 'not a valid crossover method'
        else:
            self.__crossover = crossover

        # Verifies the validity of the mutation method
        try:
            issubclass(mutation, Mutation)
            mutation = mutation()
        except TypeError:
            pass
        if not isinstance(mutation, Mutation) and mutation is not None:
            raise TypeError, 'not a valid mutation method'
        else:
            self.__mutate = mutation
Esempio n. 14
0
def nsga2_main(opt):
    #------------INITIALIZE------------------------------------------------
    opt["pop"] = lhsamp_model.lhsamp_model(opt["N"], opt)
    #LHS Sampling

    #------------EVALUATE--------------------------------------------------
    [opt["popObj"],
     opt["popCons"]] = evaluate_pop.evaluate_pop(opt, opt["pop"])
    opt["popCV"] = evaluateCV.evaluateCV(opt["popCons"])
    opt["archiveObj"] = opt["popObj"]
    #to save all objectives
    opt["archive"] = opt["pop"]
    opt["archiveCV"] = opt["popCV"]

    #-------------------PLOT INITIAL SOLUTIONS-----------------------------
    plot_population(opt, opt["popObj"])

    if os.path.isfile(opt["histfilename"]):
        os.remove(opt["histfilename"])

    # if exist(opt["histfilename"], 'file')==2:
    #     delete(opt["histfilename"]);

    #--------------- OPTIMIZATION -----------------------------------------
    funcEval = opt["N"]

    while funcEval < opt["totalFuncEval"]:  # Generation # 1 to

        M1 = np.tile(funcEval, opt["N"], 1)
        M2 = opt["pop"]
        M3 = opt["popObj"]
        M4 = (-1) * opt["popCV"]
        M = np.concatenate(M1, M2, M3, M4, axis=1)

        #dlmwrite(opt.histfilename, M, '-append', 'delimiter',' ','precision','%.10f');%history of run
        opt = mating_selection(opt)
        #--------Mating Parent Selection-------
        opt = crossover(opt)
        #-------------------Crossover-----------------
        opt = mutation(opt)
        #--------------------Mutation------------------

        #---------------EVALUATION-----------------------------------------
        [opt["popChildObj"],
         opt["popChildCons"]] = evaluate_pop(opt, opt["popChild"])
        opt["popCV"] = evaluateCV(opt["popCons"])
        opt["popChildCV"] = evaluateCV(opt["popChildCons"])

        #---------------MERGE PARENT AND CHILDREN--------------------------
        opt["totalpopObj"] = np.concatenate(opt["popChildObj"], opt["popObj"])
        opt.totalpop = np.concatenate(opt["popChild"], opt["pop"])
        opt.totalpopCV = np.concatenate(opt["popChildCV"], opt["popCV"])
        opt.totalpopCons = np.concatenate(opt["popChildCons"], opt["popCons"])

        #-----------------SURVIVAL SELECTION-------------------------------
        opt = survival_selection(opt)
        funcEval = funcEval + opt.N

        opt.popCV = evaluateCV(opt["popCons"])
        opt.archive = np.concatenate(opt["archive"], opt["pop"])
        opt.archiveObj = np.concatenate(opt["archiveObj"], opt["popObj"])
        opt.archiveCV = np.concatenate(opt["archiveCV"], opt["popCV"])

        #-------------------PLOT NEW SOLUTIONS-----------------------------

        if funcEval % 1000 == 0:
            print(funcEval)
            plot_population(opt, opt["popObj"])
        #[opt.FeasibleIndex, opt.ParetoIndex] = calculate_feasible_paretofront(opt, opt.archive, opt.archiveObj, opt.archiveCV);

    M1 = np.concatenate(funcEval, opt["N"], 1, axis=1)
    M2 = opt.pop
    M3 = opt.popObj
    M4 = (-1) * opt.popCV
    M = np.concatenate(M1, M2, M3, M4, axis=1)

    with open('opt["histfilename"]', 'w') as f:
        f.write(M)
    # dlmwrite(opt.histfilename, M, '-append', 'delimiter',' ','precision','%.10f');#history of run

    return opt