File:Simulated Annealing-2D traveller salesman problem.webm
Summary
Description |
English: Simulated annealing is a technique to optimize a functional based on the idea that a given change is not only accepted if it improves the metric, but also if it doesn't, with a probability that depends on a "temperature" T, that is gradually reduced. In this example we look for the solution of a traveller salesman problem. At each step the order two nodes are visited is swapped, and the change is accepted if it either reduces the total length, or if Exp[-(Δlength)/T] is smaller than a random number ∈[0,1]. |
Date | |
Source | https://twitter.com/j_bertolotti/status/1499723052917088266 |
Author | Jacopo Bertolotti |
Permission (Reusing this file) |
https://twitter.com/j_bertolotti/status/1030470604418428929 |
Mathematica 13.0 code
ClearAll@swap
SetAttributes[swap, HoldFirst];
swap[list_, a_, b_] := With[{temp = list[[a]]}, list[[a]] = list[[b]]; list[[b]] = temp];
dim = 30;
path = RandomSample[Range[dim], dim];
pos = Join[RandomPoint[Disk[{-0.7, -0.7}, 0.3], dim/2], RandomPoint[Disk[{0.7, 0.7}, 0.3], dim/2]];
metric[path_] := Total[Norm /@ Differences[pos[[#]] & /@ Join[path, {path[[1]]} ]]];
maxtemp = 0.5; mintemp = -8; (*log*)
tmp = Reap[Table[
Do[
tentativepath = path;
first = RandomInteger[{1, dim}];
second = RandomInteger[{1, dim}];
swap[tentativepath, first, second];
If[ N@Exp[-((metric[tentativepath] - metric[path])/10^j)] > RandomReal[{0, 1}], path = tentativepath; Sow[{j, path}];];
, {200}];
, {j, maxtemp, mintemp, -0.025}];][[2, 1]];
evo = Table[
Grid[{{
Graphics[{
PointSize[0.02], Thickness[0.008], Point@pos, Line@(pos[[#]] & /@ Join[tmp[[j, 2]], {tmp[[j, 2]][[1]]} ]),
Text[ Style[StringForm["Total length: `` (arb. units)", NumberForm[metric[tmp[[j, 2]]], {3, 2}]], Orange, Bold, FontSize -> 12], {0, 1.1}]
}, PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}}]
,
ListPlot[metric /@ tmp[[1 ;; j, 2]], PlotRange -> {{0, Dimensions[tmp][[1]]}, {0, 1.5*dim}}, PlotStyle -> {Black, PointSize[0.01]}, Axes -> False, Frame -> True, FrameLabel -> {"Iteration", "Total length (arb. units)"}, LabelStyle -> {Black, Bold}, ImageSize -> 250],
ThermometerGauge[tmp[[j, 1]], {mintemp, maxtemp}, TicksStyle -> {Opacity[0]}, GaugeLabels -> "Log(T)\n(arb. units)", LabelStyle -> {Black, Bold}]
}}]
, {j, 1, Dimensions[tmp][[1]], 20}];
ListAnimate[evo]
Licensing
I, the copyright holder of this work, hereby publish it under the following license:
![]() ![]() |
This file is made available under the Creative Commons CC0 1.0 Universal Public Domain Dedication. |
The person who associated a work with this deed has dedicated the work to the public domain by waiving all of their rights to the work worldwide under copyright law, including all related and neighboring rights, to the extent allowed by law. You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission.
|