Quick Start
This quick start guide demonstrates how to use Altbacken to optimise a continuous vector using a simple quadratic objective. It mirrors the example in the project README.
from altbacken.external.annealing import SimpleSimulatedAnnealing
from altbacken.external.neighbourhood.numeric import VectorNeighbourhood
from altbacken.external.temperature import ExponentialCooling
from altbacken.external.stop import IterationThreshold
from altbacken.external.acceptance import BoltzmannAcceptance
# Objective function: maximise negative sum of squares → minimise sum of squares
def fitness(vector: list[float]) -> float:
return -sum(x ** 2 for x in vector)
initial_solution = [5.0, 3.0, -4.0]
neighbourhood = VectorNeighbourhood(epsilon=0.5) # random perturbation within ±0.5 on each element
temperature_schedule = ExponentialCooling(initial_temperature=1000.0, cooling_rate=0.95)
stop_condition = IterationThreshold(5000) # stop after 5 000 iterations
energy_function = BoltzmannAcceptance() # Metropolis criterion
# Create the optimiser. You can customise the energy, temperature or stop condition via keywords.
sa = SimpleSimulatedAnnealing(
fitness=fitness,
neighbourhood=neighbourhood,
temperature=temperature_schedule,
stop=stop_condition,
acceptance=energy_function,
)
# Run the optimiser. The callable returns the best solution and value.
best_solution, best_value = sa(initial_solution)
print("Best solution:", best_solution)
print("Best value:", best_value)
For more details on the available neighbourhoods, temperature schedules, stop conditions and acceptance functions, consult the API reference in API Reference.