You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/num_methods/simulated_annealing.md
+78-72Lines changed: 78 additions & 72 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,115 +9,116 @@ tags:
9
9
10
10
## The problem
11
11
12
-
We are given a function $E(s)$, which calculates the potential of the state $s$. We are tasked with finding the state $s_{best}$ at which $E(s)$ is minimized. **SA** is suited for problems where the states are discrete and $E(s)$ has multiple local minima. We'll take the example of the [Travelling Salesman Problem (TSP)](https://en.wikipedia.org/wiki/Travelling_salesman_problem).
12
+
We are given a function $E(s)$, which calculates the energy of the state $s$. We are tasked with finding the state $s_{best}$ at which $E(s)$ is minimized. **SA** is suited for problems where the states are discrete and $E(s)$ has multiple local minima. We'll take the example of the [Travelling Salesman Problem (TSP)](https://en.wikipedia.org/wiki/Travelling_salesman_problem).
13
13
14
14
### Travelling Salesman Problem (TSP)
15
15
16
-
You are given a set of nodes in 2 dimensional space. Each node is characterised by its $x$ and $y$ coordinates. Your task is to find the an ordering of the nodes, which will minimise the distance to be travelled when visiting these nodes in that order.
16
+
You are given a set of nodes in 2 dimensional space. Each node is characterised by its $x$ and $y$ coordinates. Your task is to find an ordering of the nodes, which will minimise the distance to be travelled when visiting these nodes in that order.
17
17
18
-
### State
19
-
20
-
State space is the collection of all possible values that can be taken by the independent variables.
21
-
A state is a unique point in the state space of the problem. In the case of TSP, all possible paths that we can take to visit all the nodes is the state space, and any single one of these paths can be considered as a state.
22
-
23
-
### Neighbouring state
18
+
## Motivation
19
+
Annealing is a metallurgical process , wherein a material is heated up and allowed to cool, in order to allow the atoms inside to rearrange themselves in an arrangement with minimal internal energy, which in turn causes the material to have different properties. The state is the arrangement of atoms and the internal energy is the function being minimised. We can think of the original state of the atoms, as a local minima for its internal energy. To make the material rearrange its atoms, we need to motivate it to go across a region where its internal energy is not minimised in order to reach the global minima. This motivation is given by heating the material to a higher temperature.
24
20
25
-
It is a state in the state space which is close to the previous state. This usually means that we can obtain the neighbouring state from the original state using a simple transform. In the case of the Travelling Salesman Problem, a neighbouring state is obtained by randomly choosing 2 nodes, and swapping their positions in the current state.
21
+
Simulated annealing, literally, simulates this process. We start off with some random state (material) and set a high temperature (heat it up). Now, the algorithm is ready to accept states which have a higher energy than the current state, as it is motivated by the high temperature. This prevents the algorithm from getting stuck inside local minimas and move towards the global minima. As time progresses, the algorithm cools down and refuses the states with higher energy and moves into the closest minima it has found.
26
22
27
23
### The energy function E(s)
28
24
29
25
$E(s)$ is the function which needs to be minimised (or maximised). It maps every state to a real number. In the case of TSP, $E(s)$ returns the distance of travelling one full circle in the order of nodes in the state.
30
26
31
-
## The approach
27
+
### State
28
+
29
+
The state space is the domain of the energy function, E(s), and a state is any element which belongs to the state space. In the case of TSP, all possible paths that we can take to visit all the nodes is the state space, and any single one of these paths can be considered as a state.
32
30
33
-
We start of with a random state $s$. In every step, we choose a neighbouring state $s_{next}$ of the current state $s$. If $E(s_{next}) < E(s)$, then we update $s = s_{next}$. Otherwise, we use a probability acceptance function $P(E(s),E(s_{next}),T)$ which decides whether we should move to $s_{next}$ or stay at $s$. T here is the temperature, which is initially set to a high value and decays slowly with every step. The higher the temperature, the more likely it is to move to $s_{next}$.
34
-
At the same time we also keep a track of the best state $s_{best}$ across all iterations. Proceeding till convergence or time runs out.
31
+
### Neighbouring state
35
32
36
-
### How does this work?
33
+
It is a state in the state space which is close to the previous state. This usually means that we can obtain the neighbouring state from the original state using a simple transform. In the case of the Travelling Salesman Problem, a neighbouring state is obtained by randomly choosing 2 nodes, and swapping their positions in the current state.
37
34
38
-
This algorithm is called simulated annealing because we are simulating the process of annealing, wherein a material is heated up and allowed to cool, in order to allow the atoms inside to rearrange themselves in an arrangement with minimal internal energy, which in turn causes the material to have different properties. The state is the arrangement of atoms and the internal energy is the function being minimised. We can think of the original state of the atoms, as a local minima for its internal energy. To make the material rearrange its atoms, we need to motivate it to go across a region where its internal energy is not minimised in order to reach the global minima. This motivation is given by heating the material to a higher temperature.
35
+
## Algorithm
39
36
40
-
Simulated annealing, literally simulates this process. We start off with some random state (material) and set a high temperature (heat it up). Now, the algorithm is ready to accept states which have a higher energy than the current state, as it is motivated by the high value of $T$. This prevents the algorithm from getting stuck inside local minimas and move towards the global minima. As time progresses, the algorithm cools down and refuses the states with higher energy and moves into the closest minima it has found.
37
+
We start with a random state $s$. In every step, we choose a neighbouring state $s_{next}$ of the current state $s$. If $E(s_{next}) < E(s)$, then we update $s = s_{next}$. Otherwise, we use a probability acceptance function $P(E(s),E(s_{next}),T)$ which decides whether we should move to $s_{next}$ or stay at $s$. T here is the temperature, which is initially set to a high value and decays slowly with every step. The higher the temperature, the more likely it is to move to $s_{next}$.
38
+
At the same time we also keep a track of the best state $s_{best}$ across all iterations. Proceeding till convergence or time runs out.
<i>A visual representation of simulated annealing, searching for the maxima of this function with multiple local maxima.</i>.
47
45
<br>
48
-
<i>This <ahref="https://upload.wikimedia.org/wikipedia/commons/d/d5/Hill_Climbing_with_Simulated_Annealing.gif">gif</a> by [Kingpin13](https://commons.wikimedia.org/wiki/User:Kingpin13) is distributed under <ahref="https://creativecommons.org/publicdomain/zero/1.0/deed.en">CC0 1.0</a></i> license.
49
-
</center>
46
+
<i>This <ahref="https://commons.wikimedia.org/wiki/File:Hill_Climbing_with_Simulated_Annealing.gif">animation</a> by [Kingpin13](https://commons.wikimedia.org/wiki/User:Kingpin13) is distributed under <ahref="https://creativecommons.org/publicdomain/zero/1.0/deed.en">CC0 1.0</a></i> license.
47
+
48
+
### Temperature($T$) and decay($u$)
49
+
50
+
The temperature of the system quantifies the willingness of the algorithm to accept a state with a higher energy. The decay is a constant which quantifies the "cooling rate" of the algorithm. A slow cooling rate (larger $u$) is known to give better results.
This function takes in the current state, the next state and the Temperature , returning a boolean value, which tells our search whether it should move to $s_{next}$ or stay at $s$. Note that for $E_{next} < E$ , this function will always return True.
60
+
Here, $\mathcal{U}_{[0,1]}$ is a continuous uniform random value on $[0,1]$. This function takes in the current state, the next state and the temperature, returning a boolean value, which tells our search whether it should move to $s_{next}$ or stay at $s$. Note that for $E_{next} < E$ , this function will always return True, otherwise it can still make the move with probability $\exp(-\frac{E_{next}-E}{T})$, which corresponds to the [Gibbs measure](https://en.wikipedia.org/wiki/Gibbs_measure).
60
61
61
62
```cpp
62
-
boolP(double E,double E_next,double T){
63
-
double prob = (double)rand()/RAND_MAX; // Generate a random number between 0 and 1
Fill in the state class functions as appropriate. If you are trying to find a global maxima and not a minima, ensure that the $E()$ function returns negative of the function you are maximising and finally print out $-E_{best}$. Set the below parameters as per your need.
118
+
Fill in the state class functions as appropriate. If you are trying to find a global maxima and not a minima, ensure that the $E()$ function returns negative of the function you are maximizing and print $-E_{best}$ in the end. Set the below parameters as per your need.
118
119
119
120
### Parameters
120
-
- $T$ : Temperature. Set it to a higher value if you want the search to run for a longer time.
121
+
- $T$ : Initial temperature. Set it to a higher value if you want the search to run for a longer time.
121
122
- $u$ : Decay. Decides the rate of cooling. A slower cooling rate (larger value of u) usually gives better results, at the cost of running for a longer time. Ensure $u < 1$.
122
123
123
124
The number of iterations the loop will run for is given by the expression
@@ -131,47 +132,47 @@ $T = u^{-N}$
131
132
### Example implementation for TSP
132
133
```cpp
133
134
134
-
classstate{
135
+
classstate{
135
136
public:
136
-
vector<pair<int,int>> points;
137
-
138
-
state(){
139
-
{% raw %}points = {{0,0},{2,2},{0,2},{2,0},{0,1},{1,2},{2,1},{1,0}};{% endraw %}
cout << "Lenght of shortest path found : " << E_best << "\n";
173
174
cout << "Order of points in shortest path : \n";
174
-
for(auto x: best.points){
175
+
for(auto x: best.points){
175
176
cout << x.first << " " << x.second << "\n";
176
177
}
177
178
}
@@ -180,14 +181,19 @@ int main(){
180
181
## Further modifications to the algorithm:
181
182
182
183
- Add a time based exit condition to the while loop to prevent TLE
184
+
- The decay implemented above is an exponential decay. You can always replace this with a decay function as per your needs.
183
185
- The Probability acceptance function given above, prefers accepting states which are lower in energy because of the $E_{next} - E$ factor in the numerator of the exponent. You can simply remove this factor, to make the PAF independent of the difference in energies.
184
186
- The effect of the difference in energies, $E_{next} - E$, on the PAF can be increased/decreased by increasing/decreasing the base of the exponent as shown below:
185
187
```cpp
186
-
boolP(double E,double E_next,double T){
187
-
double e = 2; // set e to any real number greater than 1
188
-
double prob = (double)rand()/RAND_MAX; // Generate a random number between 0 and 1
189
-
if(pow(e,-(E_next-E)/T) > prob) return true;
190
-
else return false;
188
+
boolP(double E, double E_next, double T, mt19937 rng) {
0 commit comments