예제 #1
0
    def __init__(self, agents, shelves, orderGoods, graph_nodes, graph):

        self.agents = agents
        self.shelves = shelves
        self.orderGoods = orderGoods
        self.graph = graph
        self.graph_nodes = graph_nodes
        self.path_queues = [MyQUEUE() for i in xrange(NUM_AGENTS)]
        self.current_overall_plans = {}  # agent_id overall plans
        self.initStartgoal()
        self.population_size = 100
        self.task_chromosome = []

        for order_id in xrange(ORDER_NUM):
            for goods_class in GOODS_ORDER[order_id]:
                self.shelves[int(goods_class / 10)].in_order = order_id
                self.shelves[int(
                    goods_class /
                    10)].unloading_position = UNLOADING_POSITION[order_id]
                self.task_chromosome = self.task_chromosome + [
                    int(goods_class / 10)
                ]
#         print self.task_chromosome
#         raw_input('prompt')
# instance the GA class
        self.ga = GA(cross_rate=0.7,
                     mutation_rate=0.02,
                     population_size=self.population_size,
                     init_chromosome=self.task_chromosome,
                     chromosome_length=len(self.task_chromosome),
                     fitness_Fun=self.fitnessFun())
        self.GA_run(GA_iteration)
        self.eachAgentTask()
예제 #2
0
def run_pop_algos_for_vid():
    "run the pop algos for proj4 vid"
    # setup data to use
    data = Data('abalone', pd.read_csv(r'data/abalone.data', header=None), 8,
                False)
    # take a sample as results do not matter for this
    df = data.df.sample(100)
    data.split_data(data_frame=df)
    gen_algo = GA(1000, 4, data, max_runs=1000, mutation_rate=1)
    print("----------------------- RUNNING THE GA -----------------")
    # get chromosome object from GA
    bestC = gen_algo.run_GA()
    print("Best fitting vector From the GA")
    print(bestC.net_vector)
    client = NetworkClient(data)
    network = NeuralNetwork(data)
    new_Net = network.GADEnet(bestC.layers, bestC.net_vector)
    print("Printing testing results from the GA")
    print(client.testing(new_Net, bestC.outputs, bestC.network))
    print("----------------------- GA DONE -----------------")
    print("---------------------------------------------------")
    print("---------------------------------------------------")
    print("---------------------------------------------------")
    print("----------------------- RUNNING DE -----------------")
    de_algo = DE(10, .7, 2, 4, data, max_runs=100, mutation_rate=.03)
    bestC = de_algo.run_DE()
    print("Best fitting vector from DE")
    print(bestC.net_vector)
    client = NetworkClient(data)
    network = NeuralNetwork(data)
    new_Net = network.GADEnet(bestC.layers, bestC.net_vector)
    print("Printing testing results from DE")
    print(client.testing(new_Net, bestC.outputs, bestC.network))
    print("----------------------- DE DONE -----------------")
예제 #3
0
 def new(self, evt=None):
     self.isRunning = False
     self.ga = GA(aCrossRate=0.7,
                  aMutationRage=0.02,
                  aLifeCount=self.lifeCount,
                  aGeneLenght=len(self.citys),
                  aMatchFun=self.matchFun())
예제 #4
0
    def new(self, evt=None):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()

        self.clear()
        self.nodes = []  # 节点坐标
        self.nodes2 = []  # 节点图片对象
        for i in range(self.n):
            x = random.random() * (self.width - 60) + 30
            y = random.random() * (self.height - 60) + 30
            self.nodes.append((x, y))
            node = self.canvas.create_oval(
                x - self.__r,
                y - self.__r,
                x + self.__r,
                y + self.__r,
                fill="#ff0000",
                outline="#000000",
                tags="node",
            )
            self.nodes2.append(node)

        self.ga = GA(lifeCount=50,
                     mutationRate=0.05,
                     judge=self.judge(),
                     mkLife=self.mkLife(),
                     xFunc=self.xFunc(),
                     mFunc=self.mFunc(),
                     save=self.save())
        self.order = range(self.n)
        self.line(self.order)
예제 #5
0
def main():
    filename = FILENAMES['berlin']

    network = None
    if filename == FILENAMES['berlin']:
        network = readBerlin('./resources/' + filename)
    else:
        network = readFile('./resources/' + filename)
    gaParam = {
        'popSize': 10,
        'noGen': 1000,
        'network': network
    }
    problParam = {
        'function': pathFunction,
        'noNodes': network['noNodes']
    }

    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()

    bestFitness = []
    for i in range(gaParam['noGen'] - 1):
        ga.oneGenerationElitism()
        bestFitness.append(ga.bestChromosome().fitness)

    bestChromosome = ga.bestChromosome()
    print(bestChromosome)

    plt.plot(bestFitness)
    plt.ylabel('Best fitness')
    plt.xlabel('Generation')
    plt.show()
예제 #6
0
 def __init__(self, data, N, mating_rate=0.7, variation_rate=0.02):
     self.data = data
     self.scale_N = N  # 群体规模N
     self.mating_rate = mating_rate
     self.variation_rate = variation_rate
     self.ga = GA(data, N, mating_rate, variation_rate)
     self.distance = 0
예제 #7
0
def main():

    MIN=0
    MAX=0

    gaParam={'popSize':500,'nrGen':200}

    propParam = citire2("file.gml")

    for i in range(propParam['n']):
        print(propParam['matrix'][i])


    print(propParam['degrees'])
    print(propParam['edges'])

    propParam['function']=modularity


    ga = GA(gaParam,propParam)
    ga.initialisation()
    ga.evaluation()

    best = ga.bestChromosome()
    fitnees = best.fitness


    for i in range(gaParam['nrGen']):

        bestSolution = ga.bestChromosome()
        #print(bestSolution)
        if bestSolution.fitness > fitnees:
            best = bestSolution
            fitnees = best.fitness
        # if i%2 == 0:
        #     ga.oneGeneration()
        # else:
        print(bestSolution.fitness)
        ga.oneGenerationElitism()


    dict=[[]]
    x=best.repres
    v=[0]*propParam['n']
    k=1
    for i in range(propParam['n']):
        if v[x[i]]==0:
            v[x[i]]=k
            k+=1
            ii=i+1
            dict.append([ii])
        else:
            b=v[x[i]]
            ii=i+1
            dict[b].append(ii)

    print(k-1)

    for i in range(k):
        print(dict[i])
예제 #8
0
파일: TSP.py 프로젝트: Doublc-Qluv/code
class TSP():
    #city城市列表,init_city初始城市的序号,count次数
    def __init__(self, address, node, init_city, count):
        self.ADDRESS = address
        self.NODE = node
        self.INITCITY = init_city
        self.Count = count
        self.ga = GA(cross_rate=0.7,
                     variation_rate=0.02,
                     city_num=len(self.NODE),
                     population_count=self.Count,
                     adaptabilty=self.adaptabilty())

    #距离
    def distance(self, order):
        distance = 0
        for i in range(self.INITCITY, self.INITCITY - len(order), -1):
            distance += self.ADDRESS[order[i]][order[i + 1]]
        return distance

    #适应度为1/距离
    def adaptabilty(self):
        return lambda life: 1.0 / self.distance(life.gene)

    def run(self, n=0):
        while n > 0:
            self.ga.next()
            distance = self.distance(self.ga.best.gene)
            if n % 100 == 0:
                print("{}:{}".format(self.ga.generation, distance))
                print(self.ga.best.gene)
            n -= 1

        print("经过%d次迭代,最优解距离为:%f" % (self.ga.generation, distance))
        return self.ga.best.gene
예제 #9
0
def main(file: str):
    graph = Graph(file)
    alg = GA(graph)
    best_route = alg.loop()
    print(best_route.gen)
    print(-best_route.fitness)
    graph.show(best_route.gen)
예제 #10
0
 def __init__(self, lifeCount=100):
     self.lifeCount = lifeCount
     self.ga = GA(mutationRate=0.9,
                  lifeCount=self.lifeCount,
                  days=days_query,
                  price=price_query,
                  matchFun=self.matchFun())
예제 #11
0
 def __init__(self,address,node,init_city,count):
     self.ADDRESS=address
     self.NODE=node
     self.INITCITY=init_city
     self.Count=count
     self.ga=GA(cross_rate=0.7,variation_rate=0.02,city_num=len(self.NODE),
     population_count=self.Count,adaptabilty=self.adaptabilty())
예제 #12
0
 def restart(self):
     self.canvas.delete("line")
     self.canvas.delete("city_num")
     self.ga = GA(aCrossRate=0.7,
                  aMutationRate=0.2,
                  aLifeNum=self.lifeNum,
                  aGeneLen=len(self.citys),
                  aSsess=self.assess())
예제 #13
0
 def __init__(self, searchSet, aLifeCount=100):
     self.citys = searchSet
     self.lifeCount = aLifeCount
     self.ga = GA(aCrossRate=0.9,
                  aMutationRate=0.07,
                  aLifeCount=self.lifeCount,
                  aGeneLength=len(self.citys),
                  aMatchFun=self.matchFun())
예제 #14
0
 def __init__(self, city_file, aLifeNum = 99, aCrsRate=0.7, aMutaRate=0.7):
       self.initCitys(city_file)
       self.lifeNum = aLifeNum
       self.ga = GA(aCrossRate = aCrsRate, 
             aMutationRate = aMutaRate, 
             aLifeNum = self.lifeNum, 
             aGeneLen = len(self.citys), 
             aSsess = self.assess())
예제 #15
0
 def __init__(self, aLifeCount = 100,):
       self.initCitys()
       self.lifeCount = aLifeCount
       self.ga = GA(aCrossRate = 0.7, 
             aMutationRage = 0.02, 
             aLifeCount = self.lifeCount, 
             aGeneLenght = len(self.citys), 
             aMatchFun = self.matchFun())
예제 #16
0
class TSP(object):
    def __init__(self, aLifeCount=100):
        self.initCitys()
        self.lifeCount = aLifeCount
        self.ga = GA(aCrossRate=0.7,
                     aMutationRate=0.02,
                     aLifeCount=self.lifeCount,
                     aGeneLength=len(self.citys),
                     aMatchFun=self.matchFun())

    def initCitys(self):
        self.citys = []
        #这个文件里是34个城市的经纬度
        f = open("distanceMatrix.txt", "r", encoding='UTF-8')
        while True:
            #一行一行读取
            loci = str(f.readline())
            if loci:
                pass  # do something here
            else:
                break
            #用readline读取末尾总会有一个回车,用replace函数删除这个回车
            loci = loci.replace("\n", "")
            #按照tab键分割
            loci = loci.split("\t")
            # 中国34城市经纬度读入citys
            self.citys.append((float(loci[1]), float(loci[2]), loci[0]))

    #order是遍历所有城市的一组序列,如[1,2,3,7,6,5,4,8……]
    #distance就是计算这样走要走多长的路
    def distance(self, order):
        distance = 0.0
        #i从-1到32,-1是倒数第一个
        for i in range(-1, len(self.citys) - 1):
            index1, index2 = order[i], order[i + 1]
            city1, city2 = self.citys[index1], self.citys[index2]
            distance += math.sqrt((city1[0] - city2[0])**2 +
                                  (city1[1] - city2[1])**2)

        return distance

    #适应度函数,因为我们要从种群中挑选距离最短的,作为最优解,所以(1/距离)最长的就是我们要求的
    def matchFun(self):
        return lambda life: 1.0 / self.distance(life.gene)

    def run(self, n=0):
        while n > 0:
            self.ga.next()
            distance = self.distance(self.ga.best.gene)
            print(("%d : %f") % (self.ga.generation, distance))
            print(self.ga.best.gene)
            n -= 1
        print("经过%d次迭代,最优解距离为:%f" % (self.ga.generation, distance))
        print("遍历城市顺序为:")
        # print "遍历城市顺序为:", self.ga.best.gene
        #打印出我们挑选出的这个序列中
        for i in self.ga.best.gene:
            print(self.citys[i][2])
예제 #17
0
파일: TSP_GA_w.py 프로젝트: temaeli/Waseda
 def new(self, evt=None):
     self.isRunning = False
     order = range(len(self.citys))
     self.line(order)
     self.ga = GA(aCrossRate=0.7,
                  aMutationRage=0.02,
                  aIndividualCount=self.individualCount,
                  aGeneLenght=len(self.citys),
                  aMatchFun=self.matchFun())
예제 #18
0
파일: TSP.py 프로젝트: if1997/Skill-student
 def __init__(self, city, init_city, count):
     self.CITY = city
     self.INITCITY = init_city
     self.Count = count
     self.ga = GA(cross_rate=0.7,
                  variation_rate=0.02,
                  city_num=len(self.CITY),
                  population_count=self.Count,
                  adaptabilty=self.adaptabilty())
예제 #19
0
def desen(ret):
    seed(1)
    # plot the function to be optimised
    noDim = 1
    xref = [[generateNewValue(0, ret['noNodes'] - 1) for _ in range(noDim)]
            for _ in range(0, 1000)]
    xref.sort()
    yref = [fcEval(xi) for xi in xref]
    plt.ion()
    plt.plot(xref, yref, 'b-')
    plt.xlabel('x values')
    plt.ylabel('y = f(x) values')
    plt.show()

    # initialise de GA parameters
    #  gaParam = {'popSize' : 10, 'noGen' : 3, 'pc' : 0.8, 'pm' : 0.1}
    # problem parameters
    # problParam = {'min' : MIN, 'max' : MAX, 'function' : fcEval, 'noDim' : noDim, 'noBits' : 8}

    # store the best/average solution of each iteration (for a final plot used to anlyse the GA's convergence)
    allBestFitnesses = []
    allAvgFitnesses = []
    generations = []

    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()

    for g in range(gaParam['noGen']):
        #plotting preparation
        allPotentialSolutionsX = [c.repres for c in ga.population]
        allPotentialSolutionsY = [c.fitness for c in ga.population]
        bestSolX = ga.bestChromosome().repres
        bestSolY = ga.bestChromosome().fitness
        allBestFitnesses.append(bestSolY)
        allAvgFitnesses.append(
            sum(allPotentialSolutionsY) / len(allPotentialSolutionsY))
        generations.append(g)
        plotAFunction(xref, yref, allPotentialSolutionsX,
                      allPotentialSolutionsY, bestSolX, [bestSolY],
                      'generation: ' + str(g))

        #logic alg
        ga.oneGeneration()
        # ga.oneGenerationElitism()
        # ga.oneGenerationSteadyState()

        bestChromo = ga.bestChromosome()
        print('Best solution in generation ' + str(g) + ' is: x = ' +
              str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness))

        plt.ioff()
        best, = plt.plot(generations, allBestFitnesses, 'ro', label='best')
        mean, = plt.plot(generations, allAvgFitnesses, 'bo', label='mean')
        plt.legend([best, (best, mean)], ['Best', 'Mean'])
        plt.show()
class TSP(object):
    def __init__(
        self,
        aLifeCount=250,
    ):
        self.initCitys()
        self.lifeCount = aLifeCount
        self.ga = GA(aCrossRate=0.7,
                     aMutationRage=0.02,
                     aLifeCount=self.lifeCount,
                     aGeneLenght=len(self.citys),
                     aMatchFun=self.matchFun())

    def initCitys(self):
        self.citys = []
        self.citys.append((16, 3))
        self.citys.append((17, 39))
        self.citys.append((12, 31))
        self.citys.append((10, 60))
        self.citys.append((30, 29))
        self.citys.append((40, 4))
        self.citys.append((10, 38))
        self.citys.append((11, 40))
        self.citys.append((29, 22))
        self.citys.append((55, 45))

        self.citys.append((160, 35))
        self.citys.append((170, 88))
        self.citys.append((120, 31))
        self.citys.append((100, 60))
        self.citys.append((99, 55))
        self.citys.append((78, 87))
        self.citys.append((100, 38))
        self.citys.append((111, 40))
        self.citys.append((64, 22))
        self.citys.append((123, 123))

    def distance(self, order):
        distance = 0.0
        for i in range(-1, len(self.citys) - 1):
            index1, index2 = order[i], order[i + 1]
            city1, city2 = self.citys[index1], self.citys[index2]
            distance += math.sqrt((city1[0] - city2[0])**2 +
                                  (city1[1] - city2[1])**2)
        return distance

    def matchFun(self):
        return lambda life: 1.0 / self.distance(life.gene)

    def run(self, n=0):
        while n > 0:
            self.ga.next()
            distance = self.distance(self.ga.best.gene)
            print(self.ga.generation, float('%.5f' % distance),
                  self.ga.best.gene)
            n -= 1
예제 #21
0
 def new(self, evt=None):
     self.isRunning = False
     order = range(len(self.citys))
     self.line(order)
     self.ga = GA(aCrossRate=0.8,
                  aMutationRage=0.02,
                  aLifeCount=self.lifeCount,
                  aGeneLenght=len(self.citys),
                  aD=self.get_list(),
                  aMatchFun=self.matchFun())
예제 #22
0
def main():
    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()
    ga.oneGeneration()
    bestChromo=ga.bestChromosome()
    print('Solutia cea mai buna este: ' + str(afisare(bestChromo.repres)) + ' cost = ' + str(bestChromo.fitness))
예제 #23
0
def main():
    gaParam, problParam = initParams(FILENAMES['dolphins'])
    ga = GA(gaParam, problParam)

    ga.initialisation()
    ga.evaluation()

    currentGeneration = 0
    bestFitnessArr = []
    while currentGeneration <= gaParam['noGen']:
        ga.oneGeneration()
        bestChromosome = ga.bestChromosome()

        print('=== [Gen ' + str(currentGeneration) + '] ===')
        print(bestChromosome)
        print('Fitness: ' + str(bestChromosome.fitness))
        print('Number of communities: ' +
              str(getNumberOfCommunities(problParam, bestChromosome.repres)))
        print('')
        bestFitnessArr.append(bestChromosome.fitness)
        currentGeneration += 1

    plt.plot(bestFitnessArr)
    plt.ylabel('Best fitness')
    plt.xlabel('Generation')
    plt.show()
def main():
    graph = read_graph("exemplu.txt")
    print(graph)
    # initialise de GA parameters
    gaParam = {'popSize': 5, 'noGen': 3000, 'pc': 0.8, 'pm': 0.1}
    # problem parameters
    problParam = {'noNodes': len(graph), 'graph': graph, 'function': evalPath}

    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()

    bestChromosomes = []
    bestFitness = []

    for g in range(gaParam['noGen']):
        # logic alg
        #ga.oneGeneration()
        ga.oneGenerationElitism()
        #ga.oneGenerationSteadyState()

        bestChromo = ga.bestChromosome()
        bestChromosomes.append(bestChromo)
        bestFitness.append(bestChromo.fitness)
        print('Best solution in generation ' + str(g) + ' is:  f(x) = ' +
              str(1 / bestChromo.fitness))

    x = []
    y = []
    for i in range(len(bestFitness)):
        x.append(i)
        y.append(bestFitness[i])
    plt.plot(x, y)
    plt.show()
예제 #25
0
def main():
    reader = Reader()
    reader._init_("mediumF.txt")
    net = reader.readNetwork()

    gaParam = {"popSize": 500, "noGen": 500}
    problParam = {
        'function': roadValue,
        'noNodes': net['noNodes'],
        'net': net['mat']
    }

    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()

    stop = False
    g = -1
    solutions = []

    while not stop and g < gaParam['noGen']:
        g += 1
        ga.oneGenerationElitism()
        bestChromo = ga.bestChromosome()
        solutions.append(bestChromo)
        print('Best solution in generation ' + str(g) + ' is: x = ' +
              str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness))

    heapify(solutions)
    print(str(solutions[0]))
예제 #26
0
def main():

    crtDir = os.getcwd()
    filePath = os.path.join(crtDir, 'hardE.txt')

    #network = readNetwork1(filePath)
    network = readNetwork2(filePath)

    gaParam = {'popSize': 100, 'noGen': 100}
    problParam = {'network': network, 'function': routeFitness}

    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()
    best = []
    for g in range(gaParam['noGen']):

        #ga.oneGenerationElitism()
        ga.oneGenerationSteadyState()
        bestChromo = ga.bestChromosome()
        print('Generatia de platina ' + str(g) + ' este: x = ' +
              str(bestChromo.repres) + '\nf(x) = ' + str(bestChromo.fitness) +
              '\nDistanta = ' + str(bestChromo.distance))
        best.append(bestChromo.distance)

    plt.plot(best)
    plt.ylabel('Lungime minima')
    plt.xlabel('Generatie')
    plt.show()
예제 #27
0
def main():
    #graph = readGraph("inputFiles/easy_01_4.txt")
    #print(graph)
    #gaParam = {'popSize': 100, 'noGen': 100, 'pc': 0.8, 'pm': 0.1}
    #problParam = {'noNodes': len(graph),'graph':graph, 'function': fitness_func}

    data = readFromFile("inputFiles/hard_02_52.txt")
    gaParam = {'popSize': 100, 'noGen': 5000}

    ga = GA(gaParam, data)
    ga.initialisation()
    ga.evaluation()

    bestChromosomes = []
    bestFitness = 99999999
    bestChromosomeRepres = None

    for g in range(gaParam['noGen']):
        ga.oneGenerationElitism()
        bestChromo = ga.bestChromosome()
        if (bestChromo.fitness < bestFitness):
            bestChromosomeRepres = bestChromo.repres
            bestFitness = bestChromo.fitness
        bestChromosomes.append(bestChromo)
        print('Generation ' + str(g) + '/\n best chromosome: ' +
              str(bestChromo.repres) + '/\n  -> fitness: ' +
              str(bestChromo.fitness))

    print('\n ---------\nBest overall solution: ' + str(bestChromosomeRepres) +
          ' \n fitness = ' + str(bestFitness))
예제 #28
0
    def worker(self):

        ga = GA(5)

        initPool = ga.createRandomInitPool(5,5)

        for pos in initPool:
            
            #explore it then !!!!
            
            ga.updateMatrixData(pos[0],pos[1],True)
예제 #29
0
 def new(self, evt=None):
     self.isRunning = False
     order = range(len(self.citys))
     self.line(order)
     self.ga = GA(aCrossRate=0.65,
                  aMutationRage=0.035,
                  aLifeCount=self.lifeCount,
                  aGeneLenght=len(self.citys),
                  aMatchFun=self.matchFun())
     self.canvas.delete("dis")
     self.title("TSP")
예제 #30
0
def main(file_name, method_name, n_gens, findShortest, run_idx, restore_chkpt):
    # read in the data
    points = np.genfromtxt(file_name, delimiter=',')
    prob = int(file_name[3])
    N = points.shape[0]

    # method list
    baselines = ['random search', 'hill climber']
    name2method = {
        'random search': random_search,
        'hill climber': hill_climber,
        'GA': GA
    }

    if method_name in baselines:
        solver = name2method[method_name](points,
                                          findShortest=findShortest,
                                          prob=prob,
                                          run_idx=run_idx)
        solver.run(n_gens)
    elif method_name == 'GA':
        solver = GA(points,
                    findShortest=findShortest,
                    prob=prob,
                    run_idx=run_idx)
        solver.run(population_size=100,
                   n_gens=n_gens,
                   p_cross=0.3,
                   p_mut=0.9,
                   restore_from_chkpt=restore_chkpt)
    else:
        raise NotImplementedError(
            'unknown method: options are \'random search,\' \'hill climber,\' \'GA\''
        )

    # plot path
    path_pts = points[solver.best_path.order.astype(int), :]
    plt.plot(path_pts[:, 0],
             path_pts[:, 1],
             label='{} distance: {}'.format(method_name,
                                            solver.best_path_length),
             color='C1',
             zorder=0,
             linewidth=0.5)
    plt.scatter(points[:, 0], points[:, 1], zorder=5)
    plt.legend(loc='upper right')
    plt.show()

    # visualize fitness
    plt.plot(solver.fitness_hist, label=method_name)
    plt.legend()
    plt.xlabel('evaluations')
    plt.ylabel('fitness')
    plt.show()
예제 #31
0
파일: yaial2.py 프로젝트: averykatko/yaial
def gen_words(langs, words, weightFunc, popsize, generations, mutationProb, avg=True):
	out = {}
	for word in words:
		fitness = getFitnessFunction(langs, word, weightFunc, avg)
		population = []
		for l in langs:
			for wd, wt in l[word].items():
				population.append(wd)
		popfactor = math.ceil(popsize/len(population))
		ga = GA(population * popfactor, fitness, rs, rep, mutationProb, mut)
		ga.run(generations)
		sortedPop = sorted(ga.population, key=fitness, reverse=True)
		out[word] = list(zip(sortedPop, map(fitness, sortedPop)))
		print('best for %s: %s (fitness %f)' % (word, out[word][0][0], out[word][0][1]))
	return out
예제 #32
0
파일: TSP.py 프로젝트: wb-dirac/vrp_python
    def new(self, evt=None):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()

        self.clear()
        self.nodes = []  # 节点坐标
        self.nodes2 = []  # 节点图片对象
        for i in range(self.n):
            x = random.random() * (self.width - 60) + 30
            y = random.random() * (self.height - 60) + 30
            self.nodes.append((x, y))
            node = self.canvas.create_oval(x - self.__r,
                                           y - self.__r, x + self.__r, y + self.__r,
                                           fill="#ff0000",
                                           outline="#000000",
                                           tags="node",
                                           )
            self.nodes2.append(node)

        self.ga = GA(
            lifeCount=50,
            mutationRate=0.05,
            judge=self.judge(),
            mkLife=self.mkLife(),
            xFunc=self.xFunc(),
            mFunc=self.mFunc(),
            save=self.save()
        )
        self.order = range(self.n)
        self.line(self.order)
예제 #33
0
파일: TSP_GA.py 프로젝트: zchlong/tsp
 def __init__(self, aLifeCount = 100,):
       self.initCitys()
       self.lifeCount = aLifeCount
       self.ga = GA(aCrossRate = 0.7, 
             aMutationRage = 0.02, 
             aLifeCount = self.lifeCount, 
             aGeneLenght = len(self.citys), 
             aMatchFun = self.matchFun())
예제 #34
0
파일: TSP_GA_w.py 프로젝트: Asanebou/tsp
 def new(self, evt = None):
       self.isRunning = False
       order = range(len(self.citys))
       self.line(order)
       self.ga = GA(aCrossRate = 0.7, 
             aMutationRage = 0.02, 
             aLifeCount = self.lifeCount, 
             aGeneLenght = len(self.citys), 
             aMatchFun = self.matchFun())
예제 #35
0
파일: test.py 프로젝트: hajix/GA_TSP
def graphical_mode(tsp_file_path='./data/dj.txt', pop_size=10000, generations=100):
    global plt, fig, ax

    # matplotlib init
    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    # make ga solver
    my_ga = GA(file_path=tsp_file_path, pop_size=pop_size, generations=generations)
    my_ga.start()
    while my_ga.isAlive():
        update_plot(my_ga.best_tour)
        print('update plot')
    time.sleep(15)

    # saving model
    with open('saving.pkl', 'wr+') as f:
        pickle.dump(my_ga.best_tour, f)

    return my_ga.best_tour
예제 #36
0
def singleGA(populationCount, crossRate, murationRate, iteraNum, filename):
    cvrp = CVRP()
    name, dimension, capacity, CustomerDistance, Requirement = LoadData(filename)
    ga = GA(GeneLenght=(dimension-1), PopulationCount=populationCount, CrossRate=crossRate, MurationRate=murationRate, DistanceMat=CustomerDistance, Requirement=Requirement, Capacity=capacity)
    ga.initPopulation()
    population = copy.copy(ga.population)
    #population.append([21, 31, 19, 17, 13, 7, 26, 12, 1, 16, 30, 27, 24, 29, 18, 8, 9, 22, 15, 10, 25, 5, 20, 14, 28, 11, 4, 23, 3, 2, 6])
    bestGene = []
    minDistance = 100000
    minItera = 0
    for itera in range(iteraNum):
        newPopulation = []
        while True:
            selectNum1, selectNum2, bestNum, distance, bestPath, bestFit = ga.selectGene(population)
            child1, child2 = ga.cross(selectNum1, selectNum2)
            newPopulation.extend(ga.muration([child1, child2]))
            if len(newPopulation) > populationCount:
                newPopulation.append(population[bestNum])
                bestGene = copy.copy(population[bestNum])
                if distance < minDistance:
                    minItera = itera
                    minDistance = distance
                    population = copy.copy(newPopulation)
                break
        print minItera, bestPath, minDistance, bestFit
    return minItera, bestPath, minDistance, bestFit
예제 #37
0
파일: TSP_GA.py 프로젝트: zchlong/tsp
class TSP(object):
      def __init__(self, aLifeCount = 100,):
            self.initCitys()
            self.lifeCount = aLifeCount
            self.ga = GA(aCrossRate = 0.7, 
                  aMutationRage = 0.02, 
                  aLifeCount = self.lifeCount, 
                  aGeneLenght = len(self.citys), 
                  aMatchFun = self.matchFun())


      def initCitys(self):
            self.citys = []
            """
            for i in range(34):
                  x = random.randint(0, 1000)
                  y = random.randint(0, 1000)
                  self.citys.append((x, y))
            """

            #中国34城市经纬度
            self.citys.append((116.46, 39.92))
            self.citys.append((117.2,39.13))
            self.citys.append((121.48, 31.22))
            self.citys.append((106.54, 29.59))
            self.citys.append((91.11, 29.97))
            self.citys.append((87.68, 43.77))
            self.citys.append((106.27, 38.47))
            self.citys.append((111.65, 40.82))
            self.citys.append((108.33, 22.84))
            self.citys.append((126.63, 45.75))
            self.citys.append((125.35, 43.88))
            self.citys.append((123.38, 41.8))
            self.citys.append((114.48, 38.03))
            self.citys.append((112.53, 37.87))
            self.citys.append((101.74, 36.56))
            self.citys.append((117,36.65))
            self.citys.append((113.6,34.76))
            self.citys.append((118.78, 32.04))
            self.citys.append((117.27, 31.86))
            self.citys.append((120.19, 30.26))
            self.citys.append((119.3, 26.08))
            self.citys.append((115.89, 28.68))
            self.citys.append((113, 28.21))
            self.citys.append((114.31, 30.52))
            self.citys.append((113.23, 23.16))
            self.citys.append((121.5, 25.05))
            self.citys.append((110.35, 20.02))
            self.citys.append((103.73, 36.03))
            self.citys.append((108.95, 34.27))
            self.citys.append((104.06, 30.67))
            self.citys.append((106.71, 26.57))
            self.citys.append((102.73, 25.04))
            self.citys.append((114.1, 22.2))
            self.citys.append((113.33, 22.13))

            
      def distance(self, order):
            distance = 0.0
            for i in range(-1, len(self.citys) - 1):
                  index1, index2 = order[i], order[i + 1]
                  city1, city2 = self.citys[index1], self.citys[index2]
                  distance += math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)

                  """
                  R = 6371.004
                  Pi = math.pi 
                  LatA = city1[1]
                  LatB = city2[1]
                  MLonA = city1[0]
                  MLonB = city2[0]

                  C = math.sin(LatA*Pi / 180) * math.sin(LatB * Pi / 180) + math.cos(LatA * Pi / 180) * math.cos(LatB * Pi / 180) * math.cos((MLonA - MLonB) * Pi / 180)
                  D = R * math.acos(C) * Pi / 100
                  distance += D
                  """
            return distance


      def matchFun(self):
            return lambda life: 1.0 / self.distance(life.gene)


      def run(self, n = 0):
            while n > 0:
                  self.ga.next()
                  distance = self.distance(self.ga.best.gene)
                  print (("%d : %f") % (self.ga.generation, distance))
                  n -= 1
예제 #38
0
class TSP_WIN(object):
      def __init__(self, aRoot, aLifeCount = 1500, aWidth = 1000, aHeight = 600):
            self.root = aRoot
            self.lifeCount = aLifeCount
            self.width = aWidth
            self.height = aHeight
            self.canvas = Tkinter.Canvas(
                        self.root,
                        width = self.width,
                        height = self.height,
                  )
            self.canvas.pack(expand = Tkinter.YES, fill = Tkinter.BOTH)
            self.bindEvents()
            self.initCitys()
            self.new()
            self.title("TSP")


      def initCitys(self):
            self.citys = []
            global tuple
            txtpath=r"/home/wlw/TSP/st70.txt"
            fp=open(txtpath)
            arr=[]
            for lines in fp.readlines():
                lines=lines.replace("\n","").split(" ")
                del lines[0]

                lines = [float(i) for i in lines]
                #print lines
                lines=tuple(lines)
                arr.append(lines)
            fp.close()
            tuple=tuple(arr)
            self.citys = tuple

            #坐标变换
            minX, minY = self.citys[0][0], self.citys[0][1]
            maxX, maxY = minX, minY
            for city in self.citys[1:]:
                  if minX > city[0]:
                        minX = city[0]
                  if minY > city[1]:
                        minY = city[1]
                  if maxX < city[0]:
                        maxX = city[0]
                  if maxY < city[1]:
                        maxY = city[1]

            w = maxX - minX
            h = maxY - minY
            xoffset = 30
            yoffset = 30
            ww = self.width - 2 * xoffset
            hh = self.height - 2 * yoffset
            xx = ww / float(w)
            yy = hh / float(h)
            r = 5
            self.nodes = []
            self.nodes2 = []
            for city in self.citys:
                  x = (city[0] - minX ) * xx + xoffset
                  y = hh - (city[1] - minY) * yy + yoffset
                  self.nodes.append((x, y))
                  node = self.canvas.create_oval(x - r, y -r, x + r, y + r,
                        fill = "#ff0000",
                        outline = "#000000",
                        tags = "node",)
                  self.nodes2.append(node)

            

            
      def distance(self, order):
            distance = 0.0
            for i in range(-1, len(self.citys) - 1):
                  index1, index2 = order[i], order[i + 1]
                  city1, city2 = self.citys[index1], self.citys[index2]
                  distance += math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
            return distance


      def matchFun(self):
            return lambda life: 1.0 / self.distance(life.gene)


      def title(self, text):
            self.root.title(text)


      def line(self, order):
            self.canvas.delete("line") 
            for i in range(-1, len(order) -1):
                  p1 = self.nodes[order[i]]
                  p2 = self.nodes[order[i + 1]]
                  self.canvas.create_line(p1, p2, fill = "#000000", tags = "line")
 


      def bindEvents(self):
            self.root.bind("n", self.new)
            self.root.bind("g", self.start)
            self.root.bind("s", self.stop)


      def new(self, evt = None):
            self.isRunning = False
            order = range(len(self.citys))
            self.line(order)
            self.ga = GA(aCrossRate = 0.7,
                  aMutationRagemax = 0.05,
                  aMutationRagemin = 0.001,
                  aLifeCount = self.lifeCount, 
                  aGeneLenght = len(self.citys), 
                  aMatchFun = self.matchFun())


      def start(self, evt = None):
            self.isRunning = True
            while self.isRunning:
                  self.ga.next()
                  distance = self.distance(self.ga.best.gene)
                  print self.ga.best.gene
                  self.line(self.ga.best.gene)
                  self.title("TSP-gen: %d" % self.ga.generation)
                  print (("%d : %f") % (self.ga.generation, distance))
                  self.canvas.update()


      def stop(self, evt = None):
            self.isRunning = False


      def mainloop(self):
            self.root.mainloop()
예제 #39
0
파일: TSP.py 프로젝트: wb-dirac/vrp_python
class MyTSP(object):
    "TSP"

    def __init__(self, root, width=800, height=600, n=32):
        self.root = root
        self.width = width
        self.height = height
        self.n = n
        self.canvas = Tkinter.Canvas(
            root,
            width=self.width,
            height=self.height,
            bg="#ffffff",
            xscrollincrement=1,
            yscrollincrement=1
        )
        self.canvas.pack(expand=Tkinter.YES, fill=Tkinter.BOTH)
        self.title("TSP")
        self.__r = 5
        self.__t = None
        self.__lock = threading.RLock()

        self.__bindEvents()
        self.new()

    def __bindEvents(self):
        self.root.bind("q", self.quite)
        self.root.bind("n", self.new)
        self.root.bind("e", self.evolve)
        self.root.bind("s", self.stop)

    def title(self, s):
        self.root.title(s)

    def new(self, evt=None):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()

        self.clear()
        self.nodes = []  # 节点坐标
        self.nodes2 = []  # 节点图片对象
        for i in range(self.n):
            x = random.random() * (self.width - 60) + 30
            y = random.random() * (self.height - 60) + 30
            self.nodes.append((x, y))
            node = self.canvas.create_oval(x - self.__r,
                                           y - self.__r, x + self.__r, y + self.__r,
                                           fill="#ff0000",
                                           outline="#000000",
                                           tags="node",
                                           )
            self.nodes2.append(node)

        self.ga = GA(
            lifeCount=50,
            mutationRate=0.05,
            judge=self.judge(),
            mkLife=self.mkLife(),
            xFunc=self.xFunc(),
            mFunc=self.mFunc(),
            save=self.save()
        )
        self.order = range(self.n)
        self.line(self.order)

    def distance(self, order):
        "得到当前顺序下连线总长度"
        distance = 0
        for i in range(-1, self.n - 1):
            i1, i2 = order[i], order[i + 1]
            p1, p2 = self.nodes[i1], self.nodes[i2]
            distance += math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)

        return distance

    def mkLife(self):
        def f():
            lst = range(self.n)
            random.shuffle(lst)
            return lst

        return f

    def judge(self):
        "评估函数"
        return lambda lf, av=100: 1.0 / self.distance(lf.gene)

    def xFunc(self):
        "交叉函数"

        def f(lf1, lf2):
            p1 = random.randint(0, self.n - 1)
            p2 = random.randint(self.n - 1, self.n)
            g1 = lf2.gene[p1:p2] + lf1.gene
            # g2 = lf1.gene[p1:p2] + lf2.gene
            g11 = []
            for i in g1:
                if i not in g11:
                    g11.append(i)
            return g11

        return f

    def mFunc(self):
        "变异函数"

        def f(gene):
            p1 = random.randint(0, self.n - 2)
            p2 = random.randint(self.n - 2, self.n - 1)
            gene[p1], gene[p2] = gene[p2], gene[p1]
            return gene

        return f

    def save(self):
        def f(lf, gen):
            pass

        return f

    def evolve(self, evt=None):
        self.__lock.acquire()
        self.__running = True
        self.__lock.release()

        self.__start_time = time.time()
        while self.__running:
            self.ga.next()
            self.line(self.ga.best.gene)
            self.title("TSP - gen: %d, time: %d" % (self.ga.generation, time.time() - self.__start_time))
            self.canvas.update()

        self.__t = None

    def line(self, order):
        "将节点按 order 顺序连线"
        self.canvas.delete("line")

        def line2(i1, i2):
            p1, p2 = self.nodes[i1], self.nodes[i2]
            self.canvas.create_line(p1, p2, fill="#000000", tags="line")
            return i2

        reduce(line2, order, order[-1])

    def clear(self):
        for item in self.canvas.find_all():
            self.canvas.delete(item)

    def quite(self, evt):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()
        sys.exit()

    def stop(self, evt):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()

    def mainloop(self):
        self.root.mainloop()
예제 #40
0
파일: VRP.py 프로젝트: wb-dirac/vrp_python
class MyVRP(object):
    "TSP"

    def __init__(self, root, width=800, height=600, n=31):
        self.root = root
        self.width = width
        self.height = height
        self.n = n
        self.condition = 2000
        self.distance_dict = {}
        self.canvas = Tkinter.Canvas(
            root,
            width=self.width,
            height=self.height,
            bg="#ffffff",
            xscrollincrement=1,
            yscrollincrement=1
        )
        self.canvas.pack(expand=Tkinter.YES, fill=Tkinter.BOTH)
        self.title("TSP")
        self.__r = 5
        self.__t = None
        self.__lock = threading.RLock()

        self.__bindEvents()
        self.new()

    def __bindEvents(self):
        self.root.bind("q", self.quite)
        self.root.bind("n", self.new)
        self.root.bind("e", self.evolve)
        self.root.bind("s", self.stop)

    def title(self, s):
        self.root.title(s)

    def new(self, evt=None):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()

        self.clear()
        self.nodes = []  # 节点坐标
        self.nodes2 = []  # 节点图片对象
        x, y = self.width, self.height
        self.start = (x, y)
        self.canvas.create_oval(x - self.__r,
                                y - self.__r, x + self.__r, y + self.__r,
                                fill="#00ff00",
                                outline="#000000",
                                tags="O",
                                )
        for i in range(self.n):
            x = random.random() * (self.width - 60) + 30
            y = random.random() * (self.height - 60) + 30
            self.nodes.append((x, y))
            node = self.canvas.create_oval(x - self.__r,
                                           y - self.__r, x + self.__r, y + self.__r,
                                           fill="#ff0000",
                                           outline="#000000",
                                           tags="node",
                                           )
            self.nodes2.append(node)

        self.ga = GA(
            lifeCount=50,
            mutationRate=0.05,
            judge=self.judge(),
            mkLife=self.mkLife(),
            xFunc=self.xFunc(),
            mFunc=self.mFunc(),
            save=self.save()
        )
        self.order = range(self.n)
        init_life = Life(self, self.order)
        jg = self.judge()
        jg(init_life)
        self.line(init_life)

    def distance(self, order):
        "得到当前顺序下连线总长度"
        distance = 0
        for i in range(-1, self.n - 1):
            i1, i2 = order[i], order[i + 1]
            p1, p2 = self.nodes[i1], self.nodes[i2]
            distance += math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)

        return distance

    def mkLife(self):
        def f():
            lst = range(self.n)
            random.shuffle(lst)
            return lst

        return f

    def judge(self):
        "评估函数"

        def f(lf, av=100):
            lf.separate_indexs = []
            path = lf.gene
            path_len = len(lf.gene)  # 路径长度,不包括起点
            i = 0  # 路径中 node 的指针
            p1 = self.start
            total_distance = 0
            one_distance = 0
            while i < path_len:
                p2 = self.nodes[path[i]]
                # if (p1, p2) not in self.distance_dict:
                #     self.distance_dict[(p1, p2)] = math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
                # distance = self.distance_dict[(p1, p2)]
                distance = math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
                if one_distance + distance > self.condition:
                    # 重置迭代变量
                    if p1 == self.start:
                        raise RuntimeError("point{}far from{}".format(p2, p1))
                    one_distance = 0
                    p1 = self.start
                    lf.separate_indexs.append(i)
                else:
                    p1 = p2
                    one_distance += distance
                    total_distance += distance
                    i += 1
            lf.set_distance(total_distance)
            lf.separate_indexs.append(i)
            return 1 / (len(lf.separate_indexs) * 0 + total_distance)

        # return lambda lf, av=100: 1.0 / self.distance(lf.gene)
        return f

    def xFunc(self):
        "交叉函数"

        def f(lf1, lf2):
            p1 = random.randint(0, self.n - 1)
            p2 = random.randint(self.n - 1, self.n)
            g1 = lf2.gene[p1:p2] + lf1.gene
            # g2 = lf1.gene[p1:p2] + lf2.gene
            g11 = []
            for i in g1:
                if i not in g11:
                    g11.append(i)
            return g11

        return f

    def mFunc(self):
        "变异函数"

        def f(gene):
            p1 = random.randint(0, self.n - 2)
            p2 = random.randint(self.n - 2, self.n - 1)
            gene[p1], gene[p2] = gene[p2], gene[p1]
            return gene

        return f

    def save(self):
        def f(lf, gen):
            pass

        return f

    def evolve(self, evt=None):
        self.__lock.acquire()
        self.__running = True
        self.__lock.release()
        self.__start_time = time.time()
        while self.__running:
            self.ga.next()
            self.line(self.ga.best)
            self.title("TSP - gen: %d, time: %d" % (self.ga.generation, time.time() - self.__start_time))
            self.canvas.update()

        self.__t = None

    def line(self, life):
        order = life.gene
        "将节点按 order 顺序连线 以life.separete_indexs 分割"
        self.canvas.delete("line")

        def line2(i1, i2):
            p1 = self.start if i1 == -1 else self.nodes[i1]
            p2 = self.nodes[i2]
            self.canvas.create_line(p1, p2, fill="#000000", tags="line")
            return i2

        start_number = 0
        for i in life.separate_indexs:
            reduce(line2, order[start_number:i], -1)
            start_number = i

    def clear(self):
        for item in self.canvas.find_all():
            self.canvas.delete(item)

    def quite(self, evt):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()
        sys.exit()

    def stop(self, evt):
        self.__lock.acquire()
        self.__running = False
        self.__lock.release()

    def mainloop(self):
        self.root.mainloop()
예제 #41
0
파일: TSP_GA.py 프로젝트: ZhangJianshu3/TSP
class TSP(object):
      def __init__(self, aLifeCount = 1500,):
            self.initCitys()
            self.lifeCount = aLifeCount
            self.ga = GA(aCrossRate = 0.8,
                  aMutationRagemax = 0.5,
                  aMutationRagemin = 0.08,
                  aLifeCount = self.lifeCount, 
                  aGeneLenght = len(self.citys), 
                  aMatchFun = self.matchFun())


      def initCitys(self):
            self.citys = []
            global tuple
            txtpath=r"/home/wlw/TSP/st70.txt"
            fp=open(txtpath)
            arr=[]
            for lines in fp.readlines():
                lines=lines.replace("\n","").split(" ")
                del lines[0]

                lines = [float(i) for i in lines]
                #print lines
                lines=tuple(lines)
                arr.append(lines)
            fp.close()
            tuple=tuple(arr)
            self.citys = tuple

            
      def distance(self, order):
            distance = 0.0
            for i in range(-1, len(self.citys) - 1):
                  index1, index2 = order[i], order[i + 1]
                  city1, city2 = self.citys[index1], self.citys[index2]
                  distance += math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)

                  """
                  R = 6371.004
                  Pi = math.pi 
                  LatA = city1[1]
                  LatB = city2[1]
                  MLonA = city1[0]
                  MLonB = city2[0]

                  C = math.sin(LatA*Pi / 180) * math.sin(LatB * Pi / 180) + math.cos(LatA * Pi / 180) * math.cos(LatB * Pi / 180) * math.cos((MLonA - MLonB) * Pi / 180)
                  D = R * math.acos(C) * Pi / 100
                  distance += D
                  """
            return distance


      def matchFun(self):
            return lambda life: 1.0 / self.distance(life.gene)


      def run(self, n = 0):
            while n > 0:
                  self.ga.next()
                  distance = self.distance(self.ga.best.gene)
                  print self.ga.best.gene
                  print (("%d : %f") % (self.ga.generation, distance))
                  n -= 1
예제 #42
0
 def __init__(self):
     GA.__init__(self)
     self.prevSolution = None
     self.prevAvg = -1
     self.currentAvg = -1
예제 #43
0
            self.make_next_gen()
            print self.pop
          #  print self.bests
            print self.best


if __name__ == "__main__":
    from GA import GA
    ss = []
    gs = []
    for i in range(10):
        pop = [''.join(str(random.choice(['1','0'])) for _ in xrange(20)) for _ in xrange(20) ]
        s = SA(e=True,func=k_fit,n=20,p=20,mu=0.0) 
        s.pop = pop
        s.run(100)
        g = GA(func = k_fit,n=20, p =20,e=True, mu=0.0)
        g.pop = pop
        g.run(100)
        ss.append(s.bests_f)
        gs.append(g.bests_f)
        #plt.plot(s.av_f)
        #plt.plot(g.av_f)
    #    plt.plot(s.bests_f)
    #    plt.plot(g.bests_f)
    #    plt.show()
   # pass

    ss = reduce(np.add,ss)
    gs = reduce(np.add,gs)
    plt.plot(map(lambda x: x/10., ss))
    plt.plot(map(lambda x: x/10., gs))
예제 #44
0
def doubleGA(populationCount, crossRate1, murationRate1, crossRate2, murationRate2, iteraNum, filename):
    cvrp = CVRP()
    name, dimension, capacity, CustomerDistance, Requirement = LoadData(filename)
    ga1 = GA(GeneLenght=(dimension-1), PopulationCount=populationCount, CrossRate=crossRate1, MurationRate=murationRate1, DistanceMat=CustomerDistance, Requirement=Requirement, Capacity=capacity)
    ga2 = GA(GeneLenght=(dimension-1), PopulationCount=populationCount, CrossRate=crossRate2, MurationRate=murationRate2, DistanceMat=CustomerDistance, Requirement=Requirement, Capacity=capacity)
    ga1.initPopulation()
    ga2.initPopulation()
    population1 = copy.copy(ga1.population)
    population2 = copy.copy(ga2.population)
    bestGene = []
    minDistance = 100000
    minItera = 0
    for itera in range(0,iteraNum):
        newPopulation1 = []
        newPopulation2 = []
        while True:
            #选择两个父亲,生成两个子代后变异放入新种群
            selectNum1, selectNum2, bestNum1, distance1, bestPath1, bestFit1 = ga1.selectGene(population1)
            child1, child2 = ga1.cross(selectNum1, selectNum2)
            newPopulation1.extend(ga1.muration([child1, child2]))

            selectNum1, selectNum2, bestNum2, distance2, bestPath2, bestFit2 = ga2.selectGene(population2)
            child1, child2 = ga2.cross(selectNum1, selectNum2)
            newPopulation2.extend(ga2.muration([child1, child2]))
            #当数量超过设定值,交换两个平行种群的解
            if len(newPopulation1) > populationCount:
                selectNum1, selectNum2, bestNum1, distance1, bestPath1, bestFit1 = ga1.selectGene(newPopulation1)
                selectNum1, selectNum2, bestNum2, distance2, bestPath2, bestFit2 = ga2.selectGene(newPopulation2)
                exPopulation1 = []
                exPopulation2 = []
                exNum1 = range(len(newPopulation1)-1)
                exNum2 = range(len(newPopulation2)-1)
                random.shuffle(exNum1)
                random.shuffle(exNum2)
                exPopulation1.append(newPopulation2[bestNum2])
                exPopulation2.append(newPopulation1[bestNum1])
                num = random.randint(5,len(newPopulation1)-5)
                count = 0
                for i in range(len(newPopulation1)):
                    if i != bestNum1:
                        if i in exNum1:
                            if count < num:
                                exPopulation2.append(newPopulation1[i])
                            else:
                                exPopulation1.append(newPopulation1[i])
                        else:
                            exPopulation1.append(newPopulation1[i])
                        count = count + 1
                if newPopulation1[bestNum1] in exPopulation1:
                    exPopulation1.remove(newPopulation1[bestNum1])

                count = 0
                for i in range(len(newPopulation2)):
                    if i != bestNum2:
                        if i in exNum2:
                            if count < num:
                                exPopulation1.append(newPopulation2[i])
                            else:
                                exPopulation2.append(newPopulation2[i])
                        else:
                            exPopulation2.append(newPopulation2[i])
                        count = count + 1
                if newPopulation2[bestNum2] in exPopulation2:
                    exPopulation2.remove(newPopulation2[bestNum2])

                if distance1 < minDistance:
                    minItera = itera
                    minDistance = distance1
                    bestFit = bestFit1
                    bestPath =copy.copy(bestPath1)
                if distance2 < minDistance:
                    minItera = itera
                    minDistance = distance2
                    bestFit = bestFit2
                    bestPath =copy.copy(bestPath2)
                Population1 = copy.copy(exPopulation1)
                Population2 = copy.copy(exPopulation2)
                break
        print minItera, bestPath, minDistance, bestFit
    return minItera, bestPath, minDistance, bestFit
예제 #45
0
		mutation = 0.3
		copyFraction = 0.4

		dicHour = {key : 0 for key in xrange(8,20)}
		dicDepart = {key[0]: 0 for key in graph.keys()}
		dicArriv = {key[0]: 0 for key in graph.keys()}
		dicPassagenrs = {key : 0 for key in xrange(1,9)}

		for r in requests:
			dicHour[r.eStart/60] += 1
			dicDepart[r.startLocation] += 1
			dicPassagenrs[r.passengers] += 1
			dicArriv[r.endLocation] += 1

		#run GA
		test = GA(nReq, population, breeds, variability, mutation, copyFraction, objFunction)
		best = test.run()
		#best = (0,[6, 6, 1, 2, 17, 7, 5, 5, 16, 14, 18, 5, 19, 10, 5, 20, 16, 10, 1, 5, 14, 16, 16, 1, 16, 4, 14, 18, 7, 9, 13, 15, 11, 18, 3, 20, 11, 7, 2, 6, 16, 15, 17, 11, 1, 5, 7, 19, 13, 10])
		#Outputs

		#Benchmark distribution
		print("\n>>>> HOURS <<<<")
		for k in dicHour.keys():
			print ("%d -> %d" % (k, dicHour[k]))

		print("\n>>>> DEPARTURE <<<<")

		for k in dicDepart.keys():
			print ("%s -> %d" % (k, dicDepart[k]))

		print("\n>>>> ARRIVED <<<<")
예제 #46
0
파일: TSP_GA_w.py 프로젝트: Asanebou/tsp
class TSP_WIN(object):
      def __init__(self, aRoot, aLifeCount = 100, aWidth = 560, aHeight = 330):
            self.root = aRoot
            self.lifeCount = aLifeCount
            self.width = aWidth
            self.height = aHeight
            self.canvas = Tkinter.Canvas(
                        self.root,
                        width = self.width,
                        height = self.height,
                  )
            self.canvas.pack(expand = Tkinter.YES, fill = Tkinter.BOTH)
            self.bindEvents()
            self.initCitys()
            self.new()
            self.title("TSP")


      def initCitys(self):
            self.citys = []

            #中国34城市经纬度
            self.citys.append((116.46, 39.92))
            self.citys.append((117.2,39.13))
            self.citys.append((121.48, 31.22))
            self.citys.append((106.54, 29.59))
            self.citys.append((91.11, 29.97))
            self.citys.append((87.68, 43.77))
            self.citys.append((106.27, 38.47))
            self.citys.append((111.65, 40.82))
            self.citys.append((108.33, 22.84))
            self.citys.append((126.63, 45.75))
            self.citys.append((125.35, 43.88))
            self.citys.append((123.38, 41.8))
            self.citys.append((114.48, 38.03))
            self.citys.append((112.53, 37.87))
            self.citys.append((101.74, 36.56))
            self.citys.append((117,36.65))
            self.citys.append((113.6,34.76))
            self.citys.append((118.78, 32.04))
            self.citys.append((117.27, 31.86))
            self.citys.append((120.19, 30.26))
            self.citys.append((119.3, 26.08))
            self.citys.append((115.89, 28.68))
            self.citys.append((113, 28.21))
            self.citys.append((114.31, 30.52))
            self.citys.append((113.23, 23.16))
            self.citys.append((121.5, 25.05))
            self.citys.append((110.35, 20.02))
            self.citys.append((103.73, 36.03))
            self.citys.append((108.95, 34.27))
            self.citys.append((104.06, 30.67))
            self.citys.append((106.71, 26.57))
            self.citys.append((102.73, 25.04))
            self.citys.append((114.1, 22.2))
            self.citys.append((113.33, 22.13))

            #坐标变换
            minX, minY = self.citys[0][0], self.citys[0][1]
            maxX, maxY = minX, minY
            for city in self.citys[1:]:
                  if minX > city[0]:
                        minX = city[0]
                  if minY > city[1]:
                        minY = city[1]
                  if maxX < city[0]:
                        maxX = city[0]
                  if maxY < city[1]:
                        maxY = city[1]

            w = maxX - minX
            h = maxY - minY
            xoffset = 30
            yoffset = 30
            ww = self.width - 2 * xoffset
            hh = self.height - 2 * yoffset
            xx = ww / float(w)
            yy = hh / float(h)
            r = 5
            self.nodes = []
            self.nodes2 = []
            for city in self.citys:
                  x = (city[0] - minX ) * xx + xoffset
                  y = hh - (city[1] - minY) * yy + yoffset
                  self.nodes.append((x, y))
                  node = self.canvas.create_oval(x - r, y -r, x + r, y + r,
                        fill = "#ff0000",
                        outline = "#000000",
                        tags = "node",)
                  self.nodes2.append(node)

            

            
      def distance(self, order):
            distance = 0.0
            for i in range(-1, len(self.citys) - 1):
                  index1, index2 = order[i], order[i + 1]
                  city1, city2 = self.citys[index1], self.citys[index2]
                  distance += math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
            return distance


      def matchFun(self):
            return lambda life: 1.0 / self.distance(life.gene)


      def title(self, text):
            self.root.title(text)


      def line(self, order):
            self.canvas.delete("line") 
            for i in range(-1, len(order) -1):
                  p1 = self.nodes[order[i]]
                  p2 = self.nodes[order[i + 1]]
                  self.canvas.create_line(p1, p2, fill = "#000000", tags = "line")
 


      def bindEvents(self):
            self.root.bind("n", self.new)
            self.root.bind("g", self.start)
            self.root.bind("s", self.stop)


      def new(self, evt = None):
            self.isRunning = False
            order = range(len(self.citys))
            self.line(order)
            self.ga = GA(aCrossRate = 0.7, 
                  aMutationRage = 0.02, 
                  aLifeCount = self.lifeCount, 
                  aGeneLenght = len(self.citys), 
                  aMatchFun = self.matchFun())


      def start(self, evt = None):
            self.isRunning = True
            while self.isRunning:
                  self.ga.next()
                  distance = self.distance(self.ga.best.gene)
                  self.line(self.ga.best.gene)
                  self.title("TSP-gen: %d" % self.ga.generation)
                  self.canvas.update()


      def stop(self, evt = None):
            self.isRunning = False


      def mainloop(self):
            self.root.mainloop()