Skip to content

Commit

Permalink
small refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
afourmy committed Feb 23, 2018
1 parent 8a2d301 commit 8294bfb
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 24 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ a valid tour. If this new tour is shorter, make the change.

![Final solution](readme/lp_solution.png)

**Note**: there is an exponentially growing number of subtour constraints, which makes this algorithm inefficient for larger instances of the TSP. One way to improve it is to use lazy constraints, i.e ignore the subtour constraints and eliminate them one by one when looking for a feasible solution.

# Genetic algorithm

![Genetic algorithm](readme/genetic_algorithm.gif)
Expand Down
5 changes: 1 addition & 4 deletions algorithms/genetic_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,7 @@ def partially_mapped_crossover(self, i1, i2):
def fill_generation(self, generation):
# we select 30 random elements and keep only the best 10
if generation:
generation = sorted(sample(generation, 30), key=self.compute_length)
# generation = list(map(self.pairwise_exchange, generation[10:]))
generation = sorted(sample(generation, 30), key=self.compute_length)[10:]
while len(generation) < 70:
generation.append(self.generate_solution())
return generation
Expand All @@ -118,8 +117,6 @@ def cycle(self, generation, **data):
ng.extend(getattr(self, crossover)(*par) if random() < cr else par)
# mutation step
ng = [getattr(self, mutation)(i) for i in ng]
print(data)
print(cr, mr, mutation, crossover)
# 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])
7 changes: 2 additions & 5 deletions flask_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def index():
@app.route('/<algorithm>', methods=['POST'])
def algorithm(algorithm):
session['best'] = float('inf')
return jsonify(*getattr(tsp, algorithm)(), False)
return jsonify(*getattr(tsp, algorithm)())


@socketio.on('genetic_algorithm')
Expand All @@ -116,10 +116,7 @@ def genetic_algorithm(data):
session['generation'], best, length = tsp.cycle(session['generation'], **data)
if length < session['best']:
session['best'] = length
emit('draw', ([best], [length], True))
else:
emit('draw', ([best], [length], False))

emit('draw', ([best], [length]))

if __name__ == '__main__':
socketio.run(app)
22 changes: 7 additions & 15 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@
var currentAlgorithm = undefined;

function tourConstruction(algorithm){
clearAll();
clearLines(polylines);
if (window.optimizationTimer) {
clearTimeout(window.optimizationTimer);
window.optimizationTimer = 0;
Expand All @@ -174,7 +174,7 @@

var generationNumber = 0;
function geneticAlgorithm() {
clearAll();
clearLines(polylines);
// we cannot use setInterval as the timer depends on the slider
// we have to use setTimeout for the speed to vary through time
function timeout() {
Expand Down Expand Up @@ -329,27 +329,19 @@
{% endif %}
}
}

// Function that clears all lines
function clearAll(){
clearLines(polylines);
clearLines(bestPolylines);
}

/* Function to draw a serie of paths, with optional arguments:
- lengths for updating the length in real-time, if createPath is not
called from another function like createIntermediatePath */

async function draw(paths, lengths, best){
async function draw(paths, lengths){
for (j = 0; j < paths.length; j++) {
// update the score
if (lengths) {
$("#score").text(Math.round(Number(lengths[j])));
}
var color = best ? '#d4222a' : '#0000ff';
var lines = best ? bestPolylines : polylines;
clearLines(lines);

var color = '#0000ff';
clearLines(polylines);
for (i = 0; i < paths[j].length - 1; i++) {

var source_lat = paths[j][i][0];
Expand All @@ -370,15 +362,15 @@
});

polyline.addTo(map);
lines.push(polyline);
polylines.push(polyline);
{% else %}
var polygonSD = WE.polygon(
[[source_lat, source_lon], [destination_lat, destination_lon],
[source_lat, source_lon]], {color: color,opacity: 20}).addTo(earth);
var polygonDS = WE.polygon(
[[destination_lat, destination_lon], [source_lat, source_lon],
[destination_lat, destination_lon]], {color: color,opacity: 20}).addTo(earth);
lines.push(polygonSD, polygonDS)
polylines.push(polygonSD, polygonDS)
{% endif %}
}
var speed = $('#base_slider').val();
Expand Down

0 comments on commit 8294bfb

Please sign in to comment.