Ejemplo n.º 1
0
def main():
    net = readFile("date2.txt")
    # print(net['mat'])
    dim = net['nrCities']

    problParams = {'dim': dim}
    gaParams = {'dimPop': 100, 'nrGen': 200}
    ga = GA(net['mat'], problParams, gaParams)
    ga.initPopulation()
    ga.evaluateFitness()

    maxFitness = -1
    bestRepres = []
    filename = "hardE_out.txt"
    f = open(filename, "w")

    for gen in range(gaParams['nrGen']):
        bestChrom = ga.bestChromosome()
        bestSolution = ga.bestChromosome().repres
        bestSolutionFitness = ga.bestChromosome().fitness

        if bestSolutionFitness > maxFitness:
            maxFitness = bestSolutionFitness
            bestRepres = bestSolution
        f.write("best chromosome in generation " + str(gen) + " is " +
                str(bestSolution) + " with distance = " +
                str(ga.getDistance(bestChrom)) + " with fitness = " +
                str(bestSolutionFitness) + "\n")
        # ga.oneGeneration()
        ga.oneGenerationElitism()

    bestChromo = ga.bestChromosome()
    repres = bestChromo.repres
    repres.append(bestChromo.repres[0])
    # for i in range(len(repres)):
    #  repres[i] += 1

    f.write("best solution over all: " + str(repres) + " with distance = " +
            str(ga.getDistance(bestChromo)) + " and fitness = " +
            str(bestChromo.fitness) + "\n")
    f.close()
def runGA():
    myWorld = World([
        [0, 0, 0, 0, 1, 0, 1, 3, 1],
        [1, 0, 1, 1, 1, 0, 2, 3, 1],
        [1, 0, 0, 1, 3, 3, 3, 3, 1],
        [3, 3, 3, 1, 3, 1, 1, 0, 1],
        [3, 1, 3, 3, 3, 1, 1, 0, 0],
        [3, 3, 1, 1, 1, 1, 0, 1, 1],
        [1, 3, 0, 1, 3, 3, 3, 3, 3],
        [0, 3, 1, 1, 3, 1, 0, 1, 3],
        [1, 3, 3, 3, 3, 1, 1, 1, 4],
    ])

    ga = GA(20, 0.05, 0.9, 2, 10)
    population = ga.initPopulation(128)
    ga.evalPopulation(population, myWorld)

    # Keep track of current generation
    generation = 1
    while ga.isTerminationConditionMet(generation, maxGenerations) == False:
        # Print fittest individual from population
        fittest = population.getFittest(0)

        print("G" + str(generation) + " Best solution (" +
              str(fittest.getFitness()) + "): " + fittest.toString())

        # Apply crossover
        population = ga.crossoverPopulation(population)

        # Apply mutation
        population = ga.mutatePopulation(population)

        # Evaluate population
        ga.evalPopulation(population, myWorld)

        # Increment the current generation
        generation += 1
    print("Stopped after " + str(maxGenerations) + " generations.")
    fittest = population.getFittest(0)
    print("Best solution (" + str(fittest.getFitness()) + "): " +
          fittest.toString())