示例#1
0
  def generateRandomSolution(self, coordinate):
	newCoor = cp.copy(coor)
	coorR = [newCoor.pop(0)]
	dt = 0
	while newCoor:
	  pos = self.getRandomCoordinate(newCoor)
	  p2 = newCoor.pop(pos)
	  d = Tsp().getDistance(coorR[-1], p2)
	  dt += d
	  coorR.append(p2)  
	dt += Tsp().getDistance(p2, coorR[0])
	coorR.append(coorR[0])
	coorR = np.array(coorR)
	return dt, coorR
示例#2
0
    def getDistanceSwap(self, coorF, posR, swap):
        dsprev = dsnext = drprev = drnext = 0

        posSNext = self.getNextPos(coorF, swap)
        posSPrev = self.getPrevPos(coorF, swap)
        posRNext = self.getNextPos(coorF, posR)
        posRPrev = self.getPrevPos(coorF, posR)

        dsnext = Tsp().getDistance(coorF[swap], coorF[posSNext])
        dsprev = Tsp().getDistance(coorF[swap], coorF[posSPrev])

        drnext = Tsp().getDistance(coorF[posR], coorF[posRNext])
        drprev = Tsp().getDistance(coorF[posR], coorF[posRPrev])

        return dsprev, dsnext, drprev, drnext
示例#3
0
    def buildRoute(self):
        print "init date: " + str(date.datetime.now())
        coorR = [coor.pop(0)]
        dt = 0
        while coor:
            d, position, p2 = self.nearestNeighbors(coorR[-1], coor)
            dt += d
            coorR.append(p2)
            cd = np.array(coorR)
            Tsp().drawTsp(cd[:, 0], cd[:, 1], dt)

        dt += Tsp().getDistance(p2, coorR[0])
        coorR.append(coorR[0])
        cd = np.array(coorR)
        Tsp().drawTsp(cd[:, 0], cd[:, 1], dt)
        print "end date: " + str(date.datetime.now())
示例#4
0
 def fartherNeighbors(self, p1, coor):
     dfn = pos = -1
     i = 0
     for item in coor[:]:
         dTemp = Tsp().getDistance(p1, item)
         if dfn == -1 or dTemp > dfn:
             dfn = dTemp
             pos = i
         i += 1
     return dfn, pos, coor[pos]
示例#5
0
 def nearestNeighbors(self, p1, coor):
     dnn = pos = -1
     i = 0
     for item in coor[:]:
         dTemp = Tsp().getDistance(p1, item)
         if dnn == -1 or dTemp < dnn:
             dnn = dTemp
             pos = i
         i += 1
     return dnn, pos, coor[pos]
示例#6
0
    def generateFather(self, coordinate):
        coorR = [coordinate.pop(0)]
        dt = 0
        while coordinate:
            d, position, p2 = NearestNeighbors().nearestNeighbors(
                coorR[-1], coordinate)
            dt += d
            coorR.append(p2)

        dt += Tsp().getDistance(coorR[-1], coorR[0])
        return dt, coorR
示例#7
0
文件: pilot.py 项目: camroga/Tsp
 def nearestNeighbors(self, coor, p1):
     d = -1
     pos = -1
     i = 0
     for item in coor[:]:
         dTemp = Tsp().getDistance(p1, item)
         if d == -1 or dTemp < d:
             d = dTemp
             pos = i
     i += 1
     return d, coor.pop(pos)
示例#8
0
文件: pilot.py 项目: camroga/Tsp
 def buildRoute(self, coor):
     #print date init#
     print "init date: " + str(dt.datetime.now())
     #create root node #
     coorBase = TspNode(coor.pop(0))
     #copy coodenates #
     coorBase.coor = cp.copy(coor)
     #build pilot with temporal node for finished path#
     self.buildPilot(coorBase, self.pilot)
     #get distance final#
     self.d += Tsp().getDistance(self.coorR[-1], self.coorR[0])
     #added initial position#
     self.coorR.append(self.coorR[0])
     #transform coordinates to print#
     cd = np.array(self.coorR)
     Tsp().drawTsp(cd[:, 0], cd[:, 1], self.d)
     #print date end#
     print "end date: " + str(dt.datetime.now())
     #print graph#
     for pre, fill, node in RenderTree(coorBase):
         print("%scoordinate:%s-distance:%s" % (pre, node.name, node.d))
示例#9
0
  def buildRoute(self):
	print "init date: " + str(date.datetime.now())
	#init solution
	d, coorR = self.generateRandomSolution(coor)  
	k=1
	while k < n:
	  dt, rs =self.generateRandomSolution(coor)
	  if dt<d:
		d=dt
		coorR = rs
		Tsp().drawTsp(coorR[:,0], coorR[:,1], d)
	  k = k+1  
	#print date end
	print "end date: " + str(date.datetime.now())
示例#10
0
    def buildRoute(self):
        print "init date: " + str(date.datetime.now())
        newCoor = cp.copy(coor)
        coorR = [newCoor.pop(0)]
        drt = dF = posF = coorF = dS = posS = coorS = 0

        while newCoor:
            # generate solution father
            dF, posF, coooF = self.generateFather(coorR[-1], newCoor)
            coorF = newCoor.pop(posF)
            # generate solution son
            if len(newCoor) > 0:
                dS, posS, coorS = self.generateMutation(coorF, newCoor)
                coorS = newCoor.pop(posS)
            else:
                dS = 0
            # evaluate best solution and added coordinate
            if dS < dF:
                drt += dS
                coorR.append(coorS)
                newCoor.insert(posF, coorF)
            else:
                drt += dF
                coorR.append(coorF)
                if dS <> 0:
                    newCoor.insert(posS, coorS)
            cd = np.array(coorR)
            Tsp().drawTsp(cd[:, 0], cd[:, 1], drt)

        # connect endpoint with initial
        drt += Tsp().getDistance(coorR[-1], coorR[0])
        coorR.append(coorR[0])
        coorR = np.array(coorR)
        # draw solution
        cd = np.array(coorR)
        Tsp().drawTsp(cd[:, 0], cd[:, 1], drt)
        print "end date: " + str(date.datetime.now())
示例#11
0
    def buildRoute(self):
        print "init date: ", date.datetime.now()
        newCoor = cp.copy(coor)
        dF, coorF = self.generateFather(newCoor)
        k = 1
        while k < self.n:
            dS, coorS = self.generateMutation(dF, coorF)
            if dS < dF:
                dF = dS
                coorF = coorS

            copyCoor = cp.copy(coorF)
            copyDF = cp.copy(dF)
            """conected last position coordinate with the firt"""
            copyCoor.append(copyCoor[0])
            cd = np.array(copyCoor)
            Tsp().drawTsp(cd[:, 0], cd[:, 1], copyDF)
            k = k + 1
        """print final solution"""
        print "distance: ", dF, "coordinates: ", coorF
        print "end date: ", date.datetime.now()
            plt.show()

for dirname, _, filenames in os.walk('log/test2'):
    for filename in filenames:
        data = {}
        with open(os.path.join(dirname, filename), 'r') as f:
            ans = int(f.readline().split(', ')[1])
            f.readline()
            line = f.readline().split(' ')
            dis = [float(line[i]) for i in range(len(line) - 1)]
            final = float(f.readline())
            dis.append(final)
            line = f.readline().split(' ')
            route = [int(line[i]) for i in range(len(line) - 1)]
            route.append(route[0])

            filename = filename.split('.')[0]
            tsp = Tsp(filename)
            nodes = tsp.get_nodes()
            plt.title('data: {}, ans: {}, final: {}'.format(
                filename, ans, int(final)))
            plt.scatter([nodes[i][0] for i in range(len(nodes))],
                        [nodes[i][1] for i in range(len(nodes))],
                        color='r')
            plt.plot([nodes[route[i]][0] for i in range(len(nodes) + 1)],
                     [nodes[route[i]][1] for i in range(len(nodes) + 1)],
                     color='b',
                     linewidth=0.5)
            plt.savefig('img/test2/{}.png'.format(filename))
            plt.show()
示例#13
0
文件: tsp-main.py 项目: upk240z/ga
# -*- coding: utf-8 -*-
from tsp import Tsp
import tkinter

SCREEN_WIDTH = 360
SCREEN_HEIGHT = 360

tsp = Tsp(
    gene_size=50,
    item_size=20,
    selection_rate=0.5,
    mutation_rate=0.3,
)

for i in range(0, 1000):
    tsp.cycle()
    print(str(tsp.generation) + 'G')

root = tkinter.Tk()
root.title('GA TSP: ' + str(tsp.generation) + 'G')
root.geometry(str(SCREEN_WIDTH) + 'x' + str(SCREEN_HEIGHT))
canvas = tkinter.Canvas(root, width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
canvas.place(x=0, y=0)

canvas.delete('all')

item = tsp.top()
distance = tsp.evaluate(item)

for start in range(len(item)):
    end = start + 1
示例#14
0
文件: test_tsp.py 项目: onlyskin/jun
import pytest

import editdistance

from main import Word
from tsp import Tsp

tsp = Tsp()
word1 = Word('apple', 'sample')
word2 = Word('orange', 'sample')
word3 = Word('banana', 'sample')
word4 = Word('pear', 'sample')
words = [word1, word2, word3, word4]

def test_it_compares_two_words_by_word_with_distance_function():
    distance = tsp._compare(word1, word2, editdistance.eval)
    assert distance == 5
    distance = tsp._compare(word1, word1, editdistance.eval)
    assert distance == 9999

def test_it_makes_distance_matrix():
    matrix = tsp._distance_matrix(words, editdistance.eval)
    assert len(matrix) == 4
    assert len(matrix[0]) == 4
    assert matrix[1][1] == 9999
    assert matrix[0][1] == 5

def test_it_makes_concorde_file_string():
    string = tsp._concorde_file_string([
        [9999, 1, 2, 5],
        [1, 9999, 2, 5],
示例#15
0
    'eil51', 'eil76', 'eil101', 'st70', 'kroA100', 'kroC100', 'kroD100',
    'lin105', 'pcb442', 'pr2392'
]
ans = [426, 538, 629, 675, 21282, 20749, 21294, 14379, 50778, 378032]

selections = [
    FitnessProportionateSelection(),
    TournamentSelection(),
    ElitismSelection()
]
crossovers = [OrderCrossover(), PMXCrossover(), CycleCrossover()]
mutations = [Insert(), Swap(), Inversion(), Scramble()]
solutions = [[1, 1, 2], [1, 2, 2], [2, 1, 2]]

for i, filename in enumerate(filenames):
    tsp = Tsp(filename)
    print(filename, ans[i])
    with open('log/test1/{}.txt'.format(filename), 'w') as f:
        start = time.time()

        f.write('{}, {}\n\n'.format(filename, ans[i]))
        for size in sizes:
            for generation in generations:
                for solution in solutions:
                    selection = selections[solution[0]]
                    crossover = crossovers[solution[1]]
                    mutation = mutations[solution[2]]
                    evolution = Evolution(tsp, size, generation, selection,
                                          crossover, mutation, select_rate,
                                          mutation_rate)
                    f.write(
示例#16
0
def _make_words(lines):
    output = []
    for word, translation, notes in lines:
        if ', ' in word:
            words = word.split(', ')
            for w in words:
                output.append(Word(w, translation, notes))
        else:
            output.append(Word(word, translation, notes))
    return output


class Word():
    def __init__(self, word, translation, notes=None):
        self.word = word
        self.translation = translation
        self.notes = notes


if __name__ == '__main__':
    tsp_solver = Tsp()
    words = words_from_tsv(sys.argv[1])
    words_in_order = words_in_order(words, tsp_solver)
    lines = [
        '\t'.join([w.word, w.translation, w.notes]) for w in words_in_order
    ]
    output = '\n'.join(lines)
    with codecs.open(sys.argv[2], 'w', 'utf-8') as f:
        f.write(output)
    # simulation
    for x in range(parameters['iterations']):
        if (x % parameters['pickup_iter']) == 0:
            for b in trashbins:
                if b.X_Y_coordinates in bins_ready_for_pickup:
                    trashbin_data.append([
                        x, b.bin_id, b.filling_rate, b.current_level,
                        b.time_since_last_collection
                    ])
            redraw_map(city, bins_ready_for_pickup, bins_not_ready_for_pickup,
                       'Trash level before the pick up')
            # bins_and_center = truck_pickup(trashbins, bins_ready_for_pickup, truck)
            bins_and_center = bins_ready_for_pickup.copy()
            bins_and_center.insert(0, parameters['garbage_center'])
            vehicles_routing = Tsp(bins_and_center, parameters['num_vehicles'])
            i = 0
            while i < len(vehicles_routing.routes):
                route = vehicles_routing.routes[i]
                itinerary_coordinates.append([])
                for coordinates_index in route[1]:
                    itinerary_coordinates[i].append(
                        bins_and_center[coordinates_index])
                i += 1

            redraw_map(city, bins_ready_for_pickup, bins_not_ready_for_pickup,
                       'Trash level at the pick up', bins_and_center,
                       itinerary_coordinates)

            for index, truck in enumerate(trucks):
                truck.update_truck_data(vehicles_routing.routes[index][0])