Sorting example

This example is meant as a demonstration of the capabilities of simulated annealing. There are of course better algorithms than metaheuristic approaches.

from collections.abc import Sequence

from altbacken.external.neighbourhood.permutation import PermutationNeighbourhood
from altbacken.external.annealing import SimpleSimulatedAnnealing
unsorted = [4, 2, 9, 7, 1, 6, 0, 8, 5, 3]

Fitness function

We will use inversion count as it provides a simple measure of the quality of a permutation and provides some local optima.

def inversion_count(seq: Sequence[int]) -> int:
    return sum(
        1 for i in range(len(seq))
        for j in range(i+1, len(seq))
        if seq[i] > seq[j]
    )

Annealing strategy

We choose a simple simulated annealing strategy with a temperature of 10000.0.

annealing: SimpleSimulatedAnnealing = SimpleSimulatedAnnealing(
    inversion_count,
    PermutationNeighbourhood(),
    10000.0
)
best_match, best_value = annealing.simulate(unsorted)

print("Best match:", best_match)
print("Best value:", best_value)
Best match: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Best value: 0