Skip to content

Commit

Permalink
pytsp flake8 part 1 before CI introduction
Browse files Browse the repository at this point in the history
  • Loading branch information
afourmy committed Mar 24, 2018
1 parent 3910ab7 commit ef100ae
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 29 deletions.
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[flake8]
max-line-length=100
ignore=E402,E266,F841
6 changes: 3 additions & 3 deletions source/algorithms/base_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def update_data(self):
self.distances = self.compute_distances()

def hav(self, angle):
return sin(angle/2)**2
return sin(angle / 2)**2

def haversine_distance(self, cityA, cityB):
coords = (*self.coords[cityA], *self.coords[cityB])
Expand All @@ -27,7 +27,7 @@ def haversine_distance(self, cityA, cityB):
a = self.hav(delta_lat) + cos(lat_cityA) * cos(lat_cityB) * self.hav(delta_lon)
c = 2 * asin(sqrt(a))
# approximate radius of the Earth: 6371 km
return c*6371
return c * 6371

def compute_distances(self):
self.distances = defaultdict(dict)
Expand All @@ -50,7 +50,7 @@ def generate_solution(self):
def compute_length(self, solution):
total_length = 0
for i in range(len(solution)):
length = self.distances[solution[i]][solution[(i+1) % len(solution)]]
length = self.distances[solution[i]][solution[(i + 1) % len(solution)]]
total_length += length
return total_length

Expand Down
16 changes: 8 additions & 8 deletions source/algorithms/genetic_algorithm.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .local_optimization import *
from random import randint, random, randrange, sample, shuffle
from .local_optimization import LocalOptmizationHeuristics
from random import randint, random, randrange, sample


class GeneticAlgorithm(LocalOptmizationHeuristics):
Expand All @@ -9,14 +9,14 @@ class GeneticAlgorithm(LocalOptmizationHeuristics):
'OC': 'order_crossover',
'MPC': 'maximal_preservative_crossover',
'PMC': 'partially_mapped_crossover'
}
}

mutations = {
'Mutation method': 'swap_mutation',
'Swap': 'swap_mutation',
'Insertion': 'insertion_mutation',
'Displacement': 'displacement_mutation'
}
}

def __init__(self):
super().__init__()
Expand Down Expand Up @@ -63,9 +63,9 @@ def order_crossover(self, i1, i2):
return ni1, ni2

def maximal_preservative_crossover(self, i1, i2):
c = len(i1)//2
c = len(i1) // 2
r = randrange(self.size + 1)
s1, s2 = (i1*2)[r:r+c], (i2*2)[r:r+c]
s1, s2 = (i1 * 2)[r:r + c], (i2 * 2)[r:r + c]
for x in s1:
i2.remove(x)
for x in s2:
Expand All @@ -89,7 +89,7 @@ def partial_mapping(self, i1, i2, ni1, ni2, a, b):

def partially_mapped_crossover(self, i1, i2):
a, b = self.crossover_cut()
ni1, ni2 = [0]*self.size, [0]*self.size
ni1, ni2 = [0] * self.size, [0] * self.size
ni1[a:b], ni2[a:b] = i1[a:b], i2[a:b]
self.partial_mapping(i1, i2, ni1, ni2, a, b)
self.partial_mapping(i2, i1, ni2, ni1, a, b)
Expand All @@ -116,7 +116,7 @@ def cycle(self, generation, **data):
for par in zip(generation[::2], generation[1::2]):
ng.extend(getattr(self, crossover)(*par) if random() < cr else par)
# mutation step
ng = [getattr(self, mutation)(i) for i in ng]
ng = [getattr(self, mutation)(i) if random() < mr else i for i in ng]
# order the generation according to the fitness value
ng = sorted(ng, key=self.compute_length)
return ng, self.format_solution(ng[0]), self.compute_length(ng[0])
14 changes: 7 additions & 7 deletions source/algorithms/linear_programming.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from .base_algorithm import *
from .base_algorithm import BaseAlgorithm
from itertools import chain, combinations
try:
from cvxopt import matrix, glpk, solvers
from numpy import concatenate, eye, float, full, ones, vstack, zeros
from cvxopt import matrix, glpk
from numpy import float, full
except ImportError:
import warnings
warnings.warn('cvxopt/numpy import failed: linear programming will not work')
Expand All @@ -27,8 +27,8 @@ def edges_to_tour(self, edges):
return tour[:-1]

def ILP_solver(self):
n, sx = len(self.distances), len(self.distances)*(len(self.distances) - 1)//2
c = [float(self.distances[i+1][j+1]) for i in range(n) for j in range(i + 1, n)]
n, sx = len(self.distances), len(self.distances) * (len(self.distances) - 1) // 2
c = [float(self.distances[i + 1][j + 1]) for i in range(n) for j in range(i + 1, n)]
G, h, A, b = [], [], [], full(n, 2, dtype=float)
for st in chain.from_iterable(combinations(range(n), r) for r in range(2, n)):
G += [[float(i in st and j in st) for i in range(n) for j in range(i + 1, n)]]
Expand All @@ -37,9 +37,9 @@ def ILP_solver(self):
A.append([float(k in (i, j)) for i in range(n) for j in range(i + 1, n)])
A, G, b, c, h = map(matrix, (A, G, b, c, h))
_, x = glpk.ilp(c, G.T, h, A.T, b, B=set(range(sx)))
reverse_mapping = [(i+1, j+1) for i in range(n) for j in range(i + 1, n)]
reverse_mapping = [(i + 1, j + 1) for i in range(n) for j in range(i + 1, n)]
tour = self.edges_to_tour([reverse_mapping[k] for k in range(sx) if x[k]])
intermediate_steps = [[]]
for point in self.format_solution(tour):
intermediate_steps.append(intermediate_steps[-1] + [point])
return intermediate_steps[2:], [self.compute_length(tour)]*n
return intermediate_steps[2:], [self.compute_length(tour)] * n
4 changes: 2 additions & 2 deletions source/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
connect_args={'check_same_thread': False},
convert_unicode=True,
echo=True
)
)

db.session = scoped_session(
sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
)
)

Base = declarative_base()
Base.query = db.session.query_property()
Expand Down
18 changes: 9 additions & 9 deletions source/flask_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,18 @@
from threading import Lock
from flask import Blueprint, Flask, jsonify, render_template, request, session
from flask_socketio import emit, SocketIO
from json import dumps, load
from json import load
from os.path import abspath, dirname, join, pardir
from sqlalchemy import exc as sql_exception
from sys import dont_write_bytecode, path
from werkzeug.utils import secure_filename
from xlrd import open_workbook
from xlrd.biffh import XLRDError
import sys

dont_write_bytecode = True
sys.dont_write_bytecode = True
path_app = dirname(abspath(__file__))
path_parent = abspath(join(path_app, pardir))
if path_app not in path:
path.append(path_app)
if path_app not in sys.path:
sys.path.append(path_app)

from algorithms.pytsp import pyTSP
from database import db, create_database
Expand Down Expand Up @@ -53,15 +52,15 @@ def index():
city.id: OrderedDict([
(property, getattr(city, property))
for property in City.properties
])
])
for city in City.query.all()
}
}
return render_template(
'index.html',
view=view,
cities=cities,
async_mode=socketio.async_mode
)
)


@bp.route('/<algorithm>', methods=['POST'])
Expand Down Expand Up @@ -123,5 +122,6 @@ def genetic_algorithm(data):
session['best'] = length
emit('draw', ([best], [length]))


if __name__ == '__main__':
socketio.run(app)

0 comments on commit ef100ae

Please sign in to comment.