Local Search

CSI 4106 Introduction to Artificial Intelligence

Marcel Turcotte

Version: Nov 21, 2026 11:29

Preamble

Message of the Day

Learning Objectives

  • Distinguish an optimization problem, its candidate states, and the search trajectory used to improve them.
  • Implement and analyze the hill-climbing algorithm, recognizing its limitations such as local maxima and plateaus.
  • Apply effective state representation strategies in problems like the 8-Queens to enhance search efficiency.
  • Explain how simulated annealing can escape local optima by accepting some worse states.
  • Analyze the influence of temperature and energy difference on the acceptance probability in simulated annealing.
  • Apply simulated annealing to TSP tours using permutation-preserving moves and a best-so-far solution.
  • Explain temperature calibration from observed cost changes and the need for controlled, repeated experiments.

Introduction

Context

  • Focus has been on finding paths in state space.

  • Some problems prioritize the goal state over the path.

    • Integrated-circuit design
    • Job shop scheduling
    • Automatic programming

8-Queens Problem

Code
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

def display_n_queens(board, width):
    n = len(board)

    # Create a checkerboard pattern
    board_matrix = np.zeros((n, n))
    for row in range(n):
        for col in range(n):
            if (row + col) % 2 == 0:
                board_matrix[row, col] = 1  # White tiles
            else:
                board_matrix[row, col] = 0.5

    # Create custom colormap: gray for 0.5 and white for 1
    cmap = ListedColormap(['lightgray', 'white'])

    # Create the plot
    fig, ax = plt.subplots(figsize=(width, width))
    ax.imshow(board_matrix, cmap=cmap, extent=(0, n, 0, n))

    # Add the queen markers
    for col in range(n):
        row = board[col]
        ax.text(col + 0.5, n - row - 0.5, '♛', fontsize=32, ha='center', va='center', color='black')

    # Add grid lines
    ax.set_xticks(np.arange(n+1), minor=True)
    ax.set_yticks(np.arange(n+1), minor=True)
    ax.grid(which='minor', color='black', linestyle='-', linewidth=2)

    # Remove axis labels and ticks
    ax.set_xticks([])
    ax.set_yticks([])
    ax.tick_params(axis='both', which='both', length=0)  # Ensure ticks are completely disabled

    plt.title(f"{n}-Queens Problem")
    plt.show()
Code
# Example board for the 8-queens problem
# Represents one valid solution
board = [0, 4, 7, 5, 2, 6, 1, 3]  

display_n_queens(board, 5)

Definition

Local search algorithms operate by searching from a start state to neighboring states, without keeping track of the paths, nor the set of states that have been reached.

Problem Definition

Find a feasible state that maximizes or minimizes an objective function.

Hill-Climbing

Hill-Climbing

Hill-Climbing

Given a maximization problem:

  • current is the initial state of problem

  • repeat

    • neighbour is a highest-valued neighbor of current
    • if value(neighbour) \le value(current) then return current
    • set current to neighbour

8-Queens

How would you represent the current state?

What constraints could the representation enforce for us?

A grid can represent the board, but does not itself enforce one queen per column.

Instead, we can represent the state as a list (\mathrm{state}), where each element corresponds to the row position of the queen in its respective column.

In other words, \mathrm{state}[i] is the row of the queen in column i.

State Representation

# Example board for the 8-queens problem
board = [0, 4, 7, 5, 2, 6, 1, 3]  # Represents one valid solution for 8-queens

display_n_queens(board, 5)

create_initial_state

import random
random.seed(7)

def create_initial_state(n):

    """Generates a random initial state with one queen per column."""

    return [random.randint(0, n - 1) for _ in range(n)]

create_initial_state

state = create_initial_state(8)
display_n_queens(state, 5)

state 
[5, 2, 6, 0, 1, 1, 5, 0]

Representation of 8-Queens

8 \times 8 chessboard.

  • Unconstrained Placement: \binom{64}{8} = 4,426,165,368 possible configurations, representing the selection of 8 squares from 64.

  • Column Constraint: Use a list of length 8, with each entry indicating the row of a queen in its respective column, resulting in 8^8 = 16,777,216 configurations.

  • Row and Column Constraints: Model board states as permutations of the 8 row indices, reducing configurations to 8! = 40,320.

create_initial_state

random.seed(7)

def create_initial_state(n):

    """Generates a permutation of numbers from 0 to n-1 as the initial state."""

    state = list(range(n))
    random.shuffle(state)

    return state

create_initial_state

Code
state = create_initial_state(8)
display_n_queens(state, 5)

state 
[6, 7, 2, 4, 0, 3, 1, 5]

calculate_conflicts

def calculate_conflicts(state):

    n = len(state)
    conflicts = 0

    for col_i in range(n):
        for col_j in range(col_i + 1, n):
            row_i = state[col_i]
            row_j = state[col_j]
            if row_i == row_j:                 # same row
                conflicts += 1
            if col_i - row_i == col_j - row_j: # same diagonal
                conflicts += 1
            if col_i + row_i == col_j + row_j: # same anti-diagonal
                conflicts += 1

    return conflicts

calculate_conflicts

Code
display_n_queens(state, 5)

Code
print("Number of conflicts: ", calculate_conflicts(state))
Number of conflicts:  5

Discussion

Propose methods for generating neighboring solutions and justify the rationale for each.

get_neighbors_rn

def get_neighbors_rn(state):

    """Move one queen to another row, keeping one queen per column."""

    neighbors = []
    n = len(state)

    for col in range(n):
        for row in range(n):
            if (state[col] != row):
              new_state = state[:] # create a copy of the state
              new_state[col] = row
              neighbors.append(new_state)

    return neighbors

get_neighbors_rn

Code
state = create_initial_state(8)
display_n_queens(state, 5)

initial_state_8 = create_initial_state(8)
print(initial_state_8)
for s in get_neighbors_rn(initial_state_8):
  print(f"{s} -> # of conflicts = {calculate_conflicts(s)}")
[7, 4, 2, 5, 1, 0, 3, 6]
[0, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 6
[1, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 5
[2, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 6
[3, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 6
[4, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 6
[5, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 8
[6, 4, 2, 5, 1, 0, 3, 6] -> # of conflicts = 5
[7, 0, 2, 5, 1, 0, 3, 6] -> # of conflicts = 4
[7, 1, 2, 5, 1, 0, 3, 6] -> # of conflicts = 4
[7, 2, 2, 5, 1, 0, 3, 6] -> # of conflicts = 3
[7, 3, 2, 5, 1, 0, 3, 6] -> # of conflicts = 5
[7, 5, 2, 5, 1, 0, 3, 6] -> # of conflicts = 3
[7, 6, 2, 5, 1, 0, 3, 6] -> # of conflicts = 4
[7, 7, 2, 5, 1, 0, 3, 6] -> # of conflicts = 4
[7, 4, 0, 5, 1, 0, 3, 6] -> # of conflicts = 5
[7, 4, 1, 5, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 3, 5, 1, 0, 3, 6] -> # of conflicts = 8
[7, 4, 4, 5, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 5, 5, 1, 0, 3, 6] -> # of conflicts = 7
[7, 4, 6, 5, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 7, 5, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 2, 0, 1, 0, 3, 6] -> # of conflicts = 7
[7, 4, 2, 1, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 2, 2, 1, 0, 3, 6] -> # of conflicts = 9
[7, 4, 2, 3, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 2, 4, 1, 0, 3, 6] -> # of conflicts = 6
[7, 4, 2, 6, 1, 0, 3, 6] -> # of conflicts = 7
[7, 4, 2, 7, 1, 0, 3, 6] -> # of conflicts = 5
[7, 4, 2, 5, 0, 0, 3, 6] -> # of conflicts = 3
[7, 4, 2, 5, 2, 0, 3, 6] -> # of conflicts = 2
[7, 4, 2, 5, 3, 0, 3, 6] -> # of conflicts = 4
[7, 4, 2, 5, 4, 0, 3, 6] -> # of conflicts = 4
[7, 4, 2, 5, 5, 0, 3, 6] -> # of conflicts = 3
[7, 4, 2, 5, 6, 0, 3, 6] -> # of conflicts = 3
[7, 4, 2, 5, 7, 0, 3, 6] -> # of conflicts = 3
[7, 4, 2, 5, 1, 1, 3, 6] -> # of conflicts = 3
[7, 4, 2, 5, 1, 2, 3, 6] -> # of conflicts = 6
[7, 4, 2, 5, 1, 3, 3, 6] -> # of conflicts = 4
[7, 4, 2, 5, 1, 4, 3, 6] -> # of conflicts = 5
[7, 4, 2, 5, 1, 5, 3, 6] -> # of conflicts = 4
[7, 4, 2, 5, 1, 6, 3, 6] -> # of conflicts = 3
[7, 4, 2, 5, 1, 7, 3, 6] -> # of conflicts = 4
[7, 4, 2, 5, 1, 0, 0, 6] -> # of conflicts = 4
[7, 4, 2, 5, 1, 0, 1, 6] -> # of conflicts = 6
[7, 4, 2, 5, 1, 0, 2, 6] -> # of conflicts = 5
[7, 4, 2, 5, 1, 0, 4, 6] -> # of conflicts = 4
[7, 4, 2, 5, 1, 0, 5, 6] -> # of conflicts = 5
[7, 4, 2, 5, 1, 0, 6, 6] -> # of conflicts = 5
[7, 4, 2, 5, 1, 0, 7, 6] -> # of conflicts = 5
[7, 4, 2, 5, 1, 0, 3, 0] -> # of conflicts = 6
[7, 4, 2, 5, 1, 0, 3, 1] -> # of conflicts = 6
[7, 4, 2, 5, 1, 0, 3, 2] -> # of conflicts = 7
[7, 4, 2, 5, 1, 0, 3, 3] -> # of conflicts = 5
[7, 4, 2, 5, 1, 0, 3, 4] -> # of conflicts = 7
[7, 4, 2, 5, 1, 0, 3, 5] -> # of conflicts = 5
[7, 4, 2, 5, 1, 0, 3, 7] -> # of conflicts = 6

get_neighbors

def get_neighbors(state):

    """Swap the rows of two queens, preserving the permutation."""

    neighbors = []
    n = len(state)

    for i in range(n):
        for j in range(i + 1, n):
            new_state = state[:]
            new_state[i], new_state[j] = new_state[j], new_state[i]
            neighbors.append(new_state)

    return neighbors

get_neighbors

Code
state = create_initial_state(8)
display_n_queens(state, 4)

print(initial_state_8)
for s in get_neighbors(initial_state_8):
  print(f"{s} -> # of conflicts = {calculate_conflicts(s)}")
[7, 4, 2, 5, 1, 0, 3, 6]
[4, 7, 2, 5, 1, 0, 3, 6] -> # of conflicts = 4
[2, 4, 7, 5, 1, 0, 3, 6] -> # of conflicts = 6
[5, 4, 2, 7, 1, 0, 3, 6] -> # of conflicts = 7
[1, 4, 2, 5, 7, 0, 3, 6] -> # of conflicts = 2
[0, 4, 2, 5, 1, 7, 3, 6] -> # of conflicts = 4
[3, 4, 2, 5, 1, 0, 7, 6] -> # of conflicts = 5
[6, 4, 2, 5, 1, 0, 3, 7] -> # of conflicts = 5
[7, 2, 4, 5, 1, 0, 3, 6] -> # of conflicts = 3
[7, 5, 2, 4, 1, 0, 3, 6] -> # of conflicts = 3
[7, 1, 2, 5, 4, 0, 3, 6] -> # of conflicts = 4
[7, 0, 2, 5, 1, 4, 3, 6] -> # of conflicts = 5
[7, 3, 2, 5, 1, 0, 4, 6] -> # of conflicts = 3
[7, 6, 2, 5, 1, 0, 3, 4] -> # of conflicts = 5
[7, 4, 5, 2, 1, 0, 3, 6] -> # of conflicts = 10
[7, 4, 1, 5, 2, 0, 3, 6] -> # of conflicts = 2
[7, 4, 0, 5, 1, 2, 3, 6] -> # of conflicts = 5
[7, 4, 3, 5, 1, 0, 2, 6] -> # of conflicts = 7
[7, 4, 6, 5, 1, 0, 3, 2] -> # of conflicts = 7
[7, 4, 2, 1, 5, 0, 3, 6] -> # of conflicts = 3
[7, 4, 2, 0, 1, 5, 3, 6] -> # of conflicts = 5
[7, 4, 2, 3, 1, 0, 5, 6] -> # of conflicts = 5
[7, 4, 2, 6, 1, 0, 3, 5] -> # of conflicts = 6
[7, 4, 2, 5, 0, 1, 3, 6] -> # of conflicts = 2
[7, 4, 2, 5, 3, 0, 1, 6] -> # of conflicts = 6
[7, 4, 2, 5, 6, 0, 3, 1] -> # of conflicts = 3
[7, 4, 2, 5, 1, 3, 0, 6] -> # of conflicts = 2
[7, 4, 2, 5, 1, 6, 3, 0] -> # of conflicts = 3
[7, 4, 2, 5, 1, 0, 6, 3] -> # of conflicts = 4

hill_climbing

def hill_climbing(current_state):

    current_conflicts = calculate_conflicts(current_state)

    while True:

        if current_conflicts == 0:
          return current_state

        neighbors = get_neighbors(current_state)

        conflicts = [calculate_conflicts(neighbor) for neighbor in neighbors]

        if (min(conflicts)) > current_conflicts:
          return None # No improvement found, stuck at local minimum

        arg_best = np.argmin(conflicts)
        current_state = neighbors[arg_best]
        current_conflicts = conflicts[arg_best]

hill_climbing (take 2)

MAX_SIDE_MOVES = 100

def hill_climbing(current_state):

    current_conflicts = calculate_conflicts(current_state)
    side_moves = 0

    while True:

        if current_conflicts == 0:
            return current_state

        neighbors = get_neighbors(current_state)

        conflicts = [calculate_conflicts(neighbor) for neighbor in neighbors]
        best_conflicts = min(conflicts)

        if best_conflicts > current_conflicts:
            return None  # Strict local minimum with nonzero conflicts

        if best_conflicts == current_conflicts:
            side_moves += 1
        else:
            side_moves = 0  # Count consecutive sideways moves

        if side_moves > MAX_SIDE_MOVES:
            return None

        best_neighbors = [neighbor for neighbor, cost in zip(neighbors, conflicts)
                          if cost == best_conflicts]
        current_state = random.choice(best_neighbors)
        current_conflicts = best_conflicts

Solve

Code
random.seed(7)

solutions = 0

explored = set()
nb_duplicates = 0

for i in range(10):
  state = create_initial_state(8)

  new_state = hill_climbing(state)

  if new_state is not None:
    display_n_queens(new_state, 6)
    if tuple(new_state) in explored:
      nb_duplicates += 1
    else:
      explored.add(tuple(new_state))
    solutions += 1

print(f"10 runs, number of solutions = {solutions}, {nb_duplicates} duplicate(s)")

10 runs, number of solutions = 10, 1 duplicate(s)

Solve (2)

Code
random.seed(7)

solutions = 0

explored = set()
nb_duplicates = 0

nb_runs = 1000

for i in range(nb_runs):

  state = create_initial_state(8)

  new_state = hill_climbing(state)

  if new_state is not None:

    if tuple(new_state) in explored:
      nb_duplicates += 1
    else:
      explored.add(tuple(new_state))

    solutions += 1

print(f"{nb_runs} runs, number of solutions = {solutions}, {len(explored)} unique solutions")
1000 runs, number of solutions = 1000, 92 unique solutions

Solve 40-Queens

40! = 8.1591528325 \times 10^{47}

Code
import time

start_time = time.time()  # Record the start time

random.seed(7)

solutions = 0

explored = set()
nb_duplicates = 0

nb_runs = 10

for i in range(nb_runs):

  state = create_initial_state(40)

  new_state = hill_climbing(state)

  if new_state is not None:

    if tuple(new_state) in explored:
      nb_duplicates += 1
    else:
      explored.add(tuple(new_state))

    solutions += 1

print(f"{nb_runs} runs, number of solutions = {solutions}, {len(explored)} unique solutions")

if explored:
    one_board = next(iter(explored))
    display_n_queens(one_board, 12)

end_time = time.time()  # Record the end time
elapsed_time = end_time - start_time  # Calculate the elapsed time

print(f"Elapsed time: {elapsed_time:.4f} seconds")
10 runs, number of solutions = 10, 10 unique solutions

Elapsed time: 3.4125 seconds

Iterations and Side Moves

Code
MAX_SIDE_MOVES = 100

def hill_climbing_counts(current_state):

    current_conflicts = calculate_conflicts(current_state)
    consecutive_side_moves = 0
    total_side_moves = 0
    iterations = 0

    while True:

        if current_conflicts == 0:
            return (iterations, total_side_moves, current_state)

        neighbors = get_neighbors(current_state)

        conflicts = [calculate_conflicts(neighbor) for neighbor in neighbors]
        best_conflicts = min(conflicts)

        if best_conflicts > current_conflicts:
            return (iterations, total_side_moves, None)

        if best_conflicts == current_conflicts:
            consecutive_side_moves += 1
        else:
            consecutive_side_moves = 0

        if consecutive_side_moves > MAX_SIDE_MOVES:
            return (iterations, total_side_moves, None)

        best_neighbors = [neighbor for neighbor, cost in zip(neighbors, conflicts)
                          if cost == best_conflicts]
        if best_conflicts == current_conflicts:
            total_side_moves += 1
        current_state = random.choice(best_neighbors)
        current_conflicts = best_conflicts
        iterations += 1
Code
random.seed(7)

solutions = 0

explored = set()
nb_duplicates = 0

nb_runs = 1000

iterations = []
sides = []

iterations_none = []
sides_none = []

for i in range(nb_runs):

  state = create_initial_state(8)

  (i, s, new_state) = hill_climbing_counts(state)

  if new_state is not None:
    iterations.append(i)
    sides.append(s)
  else:
    iterations_none.append(i)
    sides_none.append(s)

  if new_state is not None:

    if tuple(new_state) in explored:
      nb_duplicates += 1
    else:
      explored.add(tuple(new_state))

    solutions += 1

print(f"{nb_runs} runs, number of solutions = {solutions}, {len(explored)} unique solutions")
1000 runs, number of solutions = 1000, 92 unique solutions
Code
import seaborn as sns

# Compare accepted moves and sideways moves among successful runs.
fig, axes = plt.subplots(1, 2, figsize=(14, 6), sharey=True)

# Accepted moves
sns.histplot(iterations, kde=True, color='green', ax=axes[0], edgecolor='black')
axes[0].set_title("Histogram of Iterations")
axes[0].set_xlabel("Iterations")
axes[0].set_ylabel("Frequency")

# Sideways moves
sns.histplot(sides, kde=True, color='blue', ax=axes[1], edgecolor='black')

axes[1].set_title("Histogram of Side Moves")
axes[1].set_xlabel("# Side Moves")

plt.tight_layout()
plt.show()

Iterations and Side Moves

20-Queens

Code
random.seed(7)

solutions = 0

explored = set()
nb_duplicates = 0

nb_runs = 1000

iterations = []
sides = []

iterations_none = []
sides_none = []

for i in range(nb_runs):

  state = create_initial_state(20)

  (i, s, new_state) = hill_climbing_counts(state)

  if new_state is not None:
    iterations.append(i)
    sides.append(s)
  else:
    iterations_none.append(i)
    sides_none.append(s)

  if new_state is not None:

    if tuple(new_state) in explored:
      nb_duplicates += 1
    else:
      explored.add(tuple(new_state))

    solutions += 1

print(f"{nb_runs} runs, number of solutions = {solutions}, {len(explored)} unique solutions")
1000 runs, number of solutions = 1000, 1000 unique solutions
Code
# Compare accepted moves and sideways moves among successful runs.
fig, axes = plt.subplots(1, 2, figsize=(14, 6), sharey=True)

# Accepted moves
sns.histplot(iterations, kde=True, color='green', ax=axes[0], edgecolor='black')
axes[0].set_title("Histogram of Iterations")
axes[0].set_xlabel("Iterations")
axes[0].set_ylabel("Frequency")

# Sideways moves
sns.histplot(sides, kde=True, color='blue', ax=axes[1], edgecolor='black')

axes[1].set_title("Histogram of Side Moves")
axes[1].set_xlabel("# Side Moves")

plt.tight_layout()
plt.show()

20-Queens

Comparing Hill-Climbing Variants

Russell & Norvig

  • For the textbook 8-Queens setup, hill climbing gets stuck 86% of the time.
    • Successful attempts average 4 steps to a solution.
  • Permitting 100 consecutive sideways moves boosts success rate from 14% to 94%.
  • The problem space comprises 8^8 = 16,777,216 states.
    • Implementation from Russell & Norvig

Escaping a Local Optimum

What mechanisms would enable the hill climbing algorithm to escape from a local optimum, whether it be a local minimum or maximum?

Remark

Assume the optimization problem is a minimization task, where the goal is to find a solution with the minimum cost.

Simulated Annealing

Definition

Simulated annealing is a local search algorithm inspired by annealing in metallurgy. For minimization, it accepts improvements and allows some uphill moves to escape local optima. Lowering a temperature parameter makes a worsening move of a given size less likely to be accepted.

Annealing

The analogy is heating followed by controlled cooling: particles can rearrange, then settle into lower-energy configurations as temperature falls (Russell and Norvig 2020, 114).

Algorithm

Varying \Delta E

Code
# Define a fixed temperature, T
T = 1.0  # You can adjust this value as needed

# Define a range of energy changes, ΔE
delta_E = np.linspace(0, 5, 500)

# Compute the function e^(-ΔE/T)
y = np.exp(-delta_E / T)

# Plot the function
plt.figure(figsize=(8, 5))
plt.plot(delta_E, y, label=r'$e^{-\frac{\Delta E}{T}}$', color='blue')
plt.title(r'Plot of $e^{-\Delta E / T}$')
plt.xlabel(r'Energy Change ($\Delta E$)')
plt.ylabel(r'$e^{-\Delta E / T}$')
plt.ylim(0, 1.1)
plt.xlim(0, 5)
plt.grid(True)
plt.legend()
plt.show()

Varying the temperature, T

Code
# Define the energy change, ΔE
delta_E = 0.1  # You can adjust this value as needed

# Define a range of temperatures, T
T = np.linspace(0.1, 5, 500)  # Avoid T=0 to prevent division by zero

# Compute the function e^(-ΔE/T)
y = np.exp(-delta_E / T)

# Plot the function
plt.figure(figsize=(8, 5))
plt.plot(T, y, label=r'$e^{-\frac{\Delta E}{T}}$', color='blue')
plt.title(r'Plot of $e^{-\Delta E / T}$')
plt.xlabel('Temperature (T)')
plt.ylabel(r'$e^{-\Delta E / T}$')
plt.ylim(0, 1.1)
plt.xlim(0, 5)
plt.grid(True)
plt.legend()
plt.show()

Varying the temperature and \Delta E

Code
# Define a range of temperatures, T
T = np.linspace(0.1, 5, 500)  # Avoid T=0 to prevent division by zero

# Define specific values for energy change, ΔE
delta_E_values = [0.001, 0.01, 0.1, 1.0, 2.0]

# Plot the function for each ΔE
plt.figure(figsize=(10, 6))
for delta_E in delta_E_values:
    y = np.exp(-delta_E / T)
    plt.plot(T, y, label=r'$\Delta E = {:.3f}$'.format(delta_E))

# Customize the plot
plt.title(r'Plot of $e^{-\Delta E / T}$ for Different $\Delta E$ Values')
plt.xlabel('Temperature (T)')
plt.ylabel(r'$e^{-\Delta E / T}$')
plt.ylim(0, 1.1)
plt.xlim(0, 5)
plt.grid(True)
plt.legend()
plt.show()

Varying the temperature and \Delta E

What Is Guaranteed?

With suitable conditions on the neighborhood and a sufficiently slow cooling schedule, the probability of finding a global optimum can approach 1 as the run length tends to infinity (Russell and Norvig 2020, 114).

A practical run uses a finite budget. A good result, or repeated good results, does not prove optimality.

Definition

The Travelling Salesman Problem (TSP) is a classic optimization problem that seeks the shortest possible route for a salesman to visit a set of cities, returning to the origin city, while visiting each city exactly once.

Traveling Salesman

Code
# Ensure we always generate the same coordinates

np.random.seed(42)

# Generate random coordinates for the cities

num_cities = 20
coordinates = np.random.rand(num_cities, 2) * 100

# Calculate the distance matrix

distance_matrix = np.sqrt(((coordinates[:, np.newaxis] - coordinates[np.newaxis, :]) ** 2).sum(axis=2))
Code
def plot_cities(coordinates, title="Cities of the Traveling Salesman Problem"):

    """
    Plot the given coordinates representing the cities.
    
    Parameters:
    - coordinates: A 2D NumPy array of shape (n, 2) representing the (x, y) coordinates.
    - title: Title of the plot.
    """

    # Extract x and y coordinates
    x = coordinates[:, 0]
    y = coordinates[:, 1]

    plt.figure(figsize=(6, 6))

    # Plot the cities as red points
    plt.scatter(x, y, c='red', zorder=2)

    # Annotate the cities with their indices
    for i, (xi, yi) in enumerate(zip(x, y)):
        plt.annotate(str(i), (xi, yi), textcoords="offset points", xytext=(0, 5), ha='center')

    # Set the title and labels
    plt.title(title)
    plt.xlabel('X Coordinate')
    plt.ylabel('Y Coordinate')
    plt.grid(True)
    plt.axis('equal')  # Equal scaling for x and y axes
    plt.show()

plot_cities(coordinates)

Discussion

How to represent a solution?

Discussion (continued)

We use a permutation of city indices, stored in a NumPy array. Its order gives the sequence of city visits, with an implicit return to the first city.

Fix city 0 at the start: rotating a closed tour changes neither its edges nor its cost.

Random Solution

Code
def plot_tsp_path(coordinates, path=None, title="Travelling Salesman Problem"):
    """Draw city identities and a closed tour in coordinate space."""
    if path is None:
        path = np.arange(len(coordinates))
    closed_path = np.append(path, path[0])
    tour_coordinates = coordinates[closed_path]

    plt.figure(figsize=(6, 6))
    plt.scatter(coordinates[:, 0], coordinates[:, 1], c='red', zorder=2)
    for city, (x, y) in enumerate(coordinates):
        plt.annotate(str(city), (x, y), textcoords="offset points",
                     xytext=(0, 5), ha='center')
    plt.plot(tour_coordinates[:, 0], tour_coordinates[:, 1], 'b-', zorder=1)
    plt.title(title)
    plt.xlabel('X Coordinate')
    plt.ylabel('Y Coordinate')
    plt.grid(True)
    plt.axis('equal')
    plt.show()

rng = np.random.default_rng(4106)
current_route = np.concatenate(([0], rng.permutation(np.arange(1, num_cities))))
plot_tsp_path(coordinates, current_route)

Calculate the Total Distance

# Function to calculate the total distance of a given route

def calculate_total_distance(route, distance_matrix):

    total_distance = 0

    for i in range(len(route) - 1):
        total_distance += distance_matrix[route[i], route[i + 1]]

    total_distance += distance_matrix[route[-1], route[0]]  # Back to start

    return total_distance

Neighborhood

Code
plot_tsp_path(coordinates, current_route)

Generating a Neighboring Solution

How to generate a neighboring solution?

Swap Two Cities

  • Description: Exchange two distinct positions in the tour.
  • Invariant: Every city still occurs exactly once.
  • Question: How many tour edges can this change?

Reverse Segment (Inversion)

  • Description: Reverse the inclusive segment between two distinct positions.
  • Invariant: Every city still occurs exactly once.
  • Question: For symmetric distances, which edges change the tour cost?

Generating a Neighboring Solution

def get_neighbor_inversion(route, rng):
    """Reverse an inclusive segment while keeping city 0 at the start."""
    a, b = sorted(rng.choice(np.arange(1, len(route)), size=2, replace=False))
    new_route = route.copy()
    new_route[a:b + 1] = new_route[a:b + 1][::-1]
    return new_route

simulated_annealing

Code
def simulated_annealing(distance_matrix, initial_route, get_neighbor,
                        initial_temp, cooling_rate, budget, rng):
    """Minimize tour cost; budget includes the initial cost evaluation."""
    current_route = initial_route.copy()
    current_cost = calculate_total_distance(current_route, distance_matrix)
    best_route = current_route.copy()
    best_cost = current_cost
    temperature = initial_temp

    # These records support the figures; search itself needs only current/best.
    history = {"temperature": [temperature], "current_cost": [current_cost],
               "best_cost": [best_cost]}
    snapshot_evaluations = set(np.linspace(1, budget, 10, dtype=int))
    snapshots = [(1, current_route.copy(), current_cost)]

    for evaluation in range(2, budget + 1):
        candidate_route = get_neighbor(current_route, rng)
        candidate_cost = calculate_total_distance(candidate_route, distance_matrix)
        delta_E = candidate_cost - current_cost

        if delta_E <= 0 or rng.random() < np.exp(-delta_E / temperature):
            current_route = candidate_route
            current_cost = candidate_cost
            if current_cost < best_cost:
                best_route = current_route.copy()
                best_cost = current_cost

        history["temperature"].append(temperature)
        history["current_cost"].append(current_cost)
        history["best_cost"].append(best_cost)
        if evaluation in snapshot_evaluations:
            snapshots.append((evaluation, current_route.copy(), current_cost))
        temperature *= cooling_rate

    return best_route, best_cost, history, snapshots

Remarks

  • As T \to \infty, every fixed-size worsening move has acceptance probability approaching 1. The search approaches a random walk over the chosen neighborhood.

Remarks

  • As T \to 0^+, every fixed positive cost increase has acceptance probability approaching 0. Improving and equal-cost moves remain accepted.

Remarks

  • Exploration means trying alternatives that may lead to different regions of the search space.
  • Exploitation means using the available objective values to favor improvements.

Example

initial_temp = 15
cooling_rate = 0.995
budget = 1001  # One initial evaluation and 1,000 attempted moves.

Execution

Code
def plot_tsp_snapshots(coordinates, snapshots):
    fig, axes = plt.subplots(2, 5, figsize=(12, 6))
    for ax, (evaluation, route, cost) in zip(axes.flat, snapshots):
        closed_route = np.append(route, route[0])
        points = coordinates[closed_route]
        ax.scatter(coordinates[:, 0], coordinates[:, 1], c='red')
        ax.plot(points[:, 0], points[:, 1], 'b-', alpha=0.6)
        ax.set_title(f"Evaluation {evaluation}: {cost:.0f}")
        ax.set_aspect('equal')
        ax.axis('off')
    plt.tight_layout()
    plt.show()

rng = np.random.default_rng(4106)
initial_route = np.concatenate(([0], rng.permutation(np.arange(1, num_cities))))
best_route, best_cost, history, snapshots = simulated_annealing(
    distance_matrix, initial_route, get_neighbor_inversion,
    initial_temp, cooling_rate, budget, rng)
inversion_best_cost = best_cost
plot_tsp_snapshots(coordinates, snapshots)

Best Route

Code
plot_tsp_path(coordinates, best_route, f"Best Inversion Tour — Cost: {best_cost:.2f}")

Temperature and Cost

Code
def plot_sa_history(history):
    evaluations = np.arange(1, len(history["current_cost"]) + 1)
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    axes[0].plot(evaluations, history["temperature"])
    axes[0].set_title("Temperature")
    axes[0].set_xlabel("Tour evaluations")
    axes[0].set_ylabel("Temperature")
    axes[1].plot(evaluations, history["current_cost"], label="Current")
    axes[1].plot(evaluations, history["best_cost"], label="Best so far")
    axes[1].set_title("Tour Cost")
    axes[1].set_xlabel("Tour evaluations")
    axes[1].set_ylabel("Cost")
    axes[1].legend()
    plt.tight_layout()
    plt.show()

plot_sa_history(history)

Swapping Neighbors

def get_neighbor_swap(route, rng):
    """Swap two distinct positions while keeping city 0 at the start."""
    a, b = rng.choice(np.arange(1, len(route)), size=2, replace=False)
    new_route = route.copy()
    new_route[a], new_route[b] = new_route[b], new_route[a]
    return new_route

Execution

Code
# Repeat the same initialization, changing only the candidate move.
rng = np.random.default_rng(4106)
initial_route = np.concatenate(([0], rng.permutation(np.arange(1, num_cities))))
best_route, best_cost, history, snapshots = simulated_annealing(
    distance_matrix, initial_route, get_neighbor_swap,
    initial_temp, cooling_rate, budget, rng)
swap_best_cost = best_cost
plot_tsp_snapshots(coordinates, snapshots)

Best Route

Code
plot_tsp_path(coordinates, best_route, f"Best Swap Tour — Cost: {best_cost:.2f}")
print(f"Inversion best cost: {inversion_best_cost:.2f}")
print(f"Swap best cost: {swap_best_cost:.2f}")

Inversion best cost: 438.16
Swap best cost: 462.21

Temperature and Cost

Code
plot_sa_history(history)

Selecting a Neighborhood Strategy

  • A move must preserve feasibility: swap and inversion both produce valid tours.
  • It also defines the search landscape and the distribution of cost changes.
  • Compare neighborhoods under a stated budget, across multiple seeds.

Initial Temperature

How should we choose T_0 when the probability of accepting a worsening move is e^{-\Delta E/T_0}?

Use the scale of positive cost changes, which depends on both the objective and the neighborhood.

Initial Temperature: One Cost Increase

For a worsening move of size \Delta E>0 and a target probability 0<p<1:

T_0 = -\frac{\Delta E}{\ln p}.

  • With \Delta E=100 and p=0.6, T_0\approx195.8.
  • With \Delta E=10 and p=0.6, T_0\approx19.58.

Initial Temperature: A Sample of Moves

Collect positive cost changes \Delta E_1,\ldots,\Delta E_m from a fixed initial tour. Choose T_0 so that

\frac{1}{m}\sum_{i=1}^{m} e^{-\Delta E_i/T_0}=p_0.

This targets the mean acceptance probability of worsening moves.

Geometric (Exponential) Cooling

T_k=T_0\alpha^k,\qquad 0<\alpha<1.

  • Smaller \alpha: faster cooling.
  • Larger \alpha: slower cooling.
  • Choose the factor in relation to the number of attempted moves.
temperature *= cooling_rate

Choosing Search Settings

  • State the neighborhood, temperature rule, and evaluation budget.
  • Use repeated seeds and summarize typical performance and variability.
  • Choose settings on a development instance before evaluating transfer to other instances.

Conclusion

Hill climbing and simulated annealing are both local search methods.

Simulated annealing can accept worse candidates. Retaining the best solution encountered protects the result while the current state explores.

Simulated Annealing Visualization

Epilogue

Summary

  • Local search improves candidate states without maintaining a frontier of paths.
  • Representation and neighborhood determine feasibility and the search landscape.
  • Hill climbing can stop at a local optimum or cycle on a plateau; bounded sideways moves and restarts are possible responses.
  • For minimization, simulated annealing (SA) accepts changes \Delta E\le0 and accepts increases with probability e^{-\Delta E/T}.
  • Temperature should reflect proposed cost changes; sample calibration targets worsening moves.
  • Keep current and best-so-far solutions separate, and compare repeated runs under explicit budgets.

Further Readings

“The overall SA [simulated annealing] methodology is then deployed in detail on a real-life application: a large-scale aircraft trajectory planning problem involving nearly 30,000 flights at the European continental scale.”

(Gendreau and Potvin 2019, chap. 1)

Next lecture

  • We will discuss population-based algorithms.

Appendix

Remove & Reconnect

  • Description: Removes three edges from the route and reconnects the segments in the best possible way. This can generate up to 7 different routes.
  • Pros: Provides more extensive changes and can escape local optima more effectively than 2-opt.
  • Cons: More complex and computationally expensive to implement.

Insertion Move

  • Description: Select a city and move it to a different position in the route.
  • Pros: Offers a balance between small and large changes, making it useful for fine-tuning solutions.
  • Cons: May require more iterations to converge to an optimal solution.

Shuffle Subset

  • Description: Select a subset of cities in the route and randomly shuffle their order.
  • Pros: Introduces larger changes and can help escape local minima.
  • Cons: Can lead to less efficient routes if not handled carefully.

Held–Karp Algorithm

  • Introduced: 1962 by Held, Karp, and independently by Bellman.
  • Problem: Solves the Traveling Salesman Problem (TSP) using dynamic programming.
  • Time Complexity: \Theta(2^n n^2).
  • Space Complexity: \Theta(2^n n).
  • Efficiency: Better than brute-force \Theta(n!), yet still exponential.

Held–Karp Algorithm

Code
from itertools import combinations

def held_karp(distance_matrix):
    # Number of cities
    n = len(distance_matrix)

    # DP table: dp[subset][last_visited] = minimum cost to reach `last_visited` with `subset` of cities visited
    dp = {}

    # Initialize the DP table with the distances from the starting point (city 0)
    for i in range(1, n):
        dp[(1 << i, i)] = distance_matrix[0][i]

    # Iterate over all subset sizes
    for subset_size in range(2, n):
        for subset in combinations(range(1, n), subset_size):
            # Bitmask of the subset, excluding the starting city
            subset_mask = sum(1 << i for i in subset)
            for last in subset:
                # Update the DP table with the minimum cost for this subset and last city
                prev_subset_mask = subset_mask & ~(1 << last)
                dp[(subset_mask, last)] = min(
                    dp[(prev_subset_mask, k)] + distance_matrix[k][last]
                    for k in subset if k != last
                )

    # Find the minimum cost to complete the tour back to the starting point (city 0)
    full_mask = (1 << n) - 2  # All cities visited except starting city
    return min(dp[(full_mask, last)] + distance_matrix[last][0] for last in range(1, n))

# Example usage with a sample distance matrix
# distance_matrix = [
#     [0, 10, 15, 20],
#     [10, 0, 35, 25],
#     [15, 35, 0, 30],
#     [20, 25, 30, 0]
# ]
min_cost = held_karp(distance_matrix)
print(f"Using Held–Karp to find the minimum cost of TSP tour: {min_cost:.2f}")
print(f"Inversion-run gap: {100 * (inversion_best_cost - min_cost) / min_cost:.2f}%")
print(f"Swap-run gap: {100 * (swap_best_cost - min_cost) / min_cost:.2f}%")
Using Held–Karp to find the minimum cost of TSP tour: 386.43
Inversion-run gap: 13.39%
Swap-run gap: 19.61%

Other Cooling Schedules

These alternatives are supplementary. The main example and Assignment 4 use geometric cooling.

Linear Cooling

  • Description: The temperature decreases linearly with each iteration.
  • Formula: T = T_0 - \alpha \cdot k
    • T_0: Initial temperature
    • \alpha: A constant decrement
    • k: Current iteration
  • Pros: Simple to implement and understand.
  • Cons: Reaches zero after finitely many steps; stop earlier or set a positive temperature floor.
temperature = initial_temp - alpha * iteration

Logarithmic Cooling

  • Description: The temperature decreases slowly following a logarithmic function.
  • Formula: T_k = T_0\frac{\ln 2}{\ln(k+2)}
    • k\ge0: Current iteration; T_{k=0}=T_0
  • Pros: Provides a slower cooling rate, which is useful for problems that require extensive exploration of the solution space.
  • Cons: Convergence can be very slow, requiring many iterations.
temperature = initial_temp * np.log(2) / np.log(iteration + 2)

Inverse Cooling

  • Description: The temperature decreases as an inverse function of the iteration number.
  • Formula: T = \frac{T_0}{1+\alpha \cdot k}
    • \alpha: A scaling constant
    • k: Current iteration
  • Pros: Allows for a more controlled cooling process, balancing exploration and exploitation.
  • Cons: May require careful tuning of \alpha to be effective.
temperature = initial_temp / (1 + alpha * iteration)

Adaptive Cooling

  • Description: The cooling schedule is adjusted dynamically based on the performance of the algorithm.
  • Strategy: If the algorithm is not making significant progress, the cooling rate may be slowed down. Conversely, if progress is steady, the cooling rate can be increased.
  • Pros: More flexible and can adapt to the characteristics of the problem.
  • Cons: More complex to implement and requires careful design to avoid instability.
if no_significant_change_in_cost:
    temperature *= 0.99  # Slow down cooling
else:
    temperature *= 0.95  # Speed up cooling

Cooling Schedule Comparison

Code
# Parameters have different meanings across schedules.
comparison_temp = 100
geometric_factor = 0.995
linear_step = 0.1
inverse_rate = 0.01
comparison_iterations = np.arange(0, 1001)

def exponential_cooling(initial_temp, factor, iteration):
    return initial_temp * factor ** iteration

def linear_cooling(initial_temp, step, iteration):
    return max(0, initial_temp - step * iteration)

def logarithmic_cooling(initial_temp, iteration):
    return initial_temp * np.log(2) / np.log(iteration + 2)

def inverse_cooling(initial_temp, rate, iteration):
    return initial_temp / (1 + rate * iteration)

linear_temps = [linear_cooling(comparison_temp, linear_step, k)
                for k in comparison_iterations]
exponential_temps = [exponential_cooling(comparison_temp, geometric_factor, k)
                     for k in comparison_iterations]
logarithmic_temps = [logarithmic_cooling(comparison_temp, k)
                    for k in comparison_iterations]
inverse_temps = [inverse_cooling(comparison_temp, inverse_rate, k)
                 for k in comparison_iterations]

plt.figure(figsize=(8, 5))
plt.plot(comparison_iterations, exponential_temps, label='Geometric: factor 0.995')
plt.plot(comparison_iterations, linear_temps, label='Linear: decrement 0.1')
plt.plot(comparison_iterations, logarithmic_temps, label='Logarithmic')
plt.plot(comparison_iterations, inverse_temps, label='Inverse: rate 0.01')
plt.xlabel('Attempted move index')
plt.ylabel('Temperature')
plt.title('Illustrative Cooling Schedules')
plt.legend()
plt.grid(True)
plt.show()

References

Aarts, E. H. L., and J. H. M. Korst. 1989. Simulated Annealing and Boltzmann Machines : A Stochastic Approach to Combinatorial Optimization and Neural Computing. Wiley-Interscience Series in Discrete Mathematics and Optimization. Wiley.
Alex, Kwaku Peprah, Kojo Appiah Simon, and Kwame Amponsah Samuel. 2017. “An Optimal Cooling Schedule Using a Simulated Annealing Based Approach.” Applied Mathematics 08 (08): 1195–210. https://doi.org/10.4236/am.2017.88090.
Bell, Jordan, and Brett Stevens. 2009. “A Survey of Known Results and Research Areas for n-Queens.” Discrete Mathematics 309 (1): 1–31. https://doi.org/https://doi.org/10.1016/j.disc.2007.12.043.
Bellman, Richard. 1962. “Dynamic Programming Treatment of the Travelling Salesman Problem.” Journal of the ACM (JACM) 9 (1): 61–63. https://doi.org/10.1145/321105.321111.
Ben-Ameur, Walid. 2004. “Computing the Initial Temperature of Simulated Annealing.” Computational Optimization and Applications 29 (3): 369–85. https://doi.org/10.1023/b:coap.0000044187.23143.bd.
Gendreau, M., and J. Y. Potvin. 2019. Handbook of Metaheuristics. International Series in Operations Research & Management Science. Springer International Publishing. https://books.google.com.ag/books?id=RbfFwQEACAAJ.
Held, Michael, and Richard M. Karp. 1962. “A Dynamic Programming Approach to Sequencing Problems.” Journal of the Society for Industrial and Applied Mathematics 10 (1): 196–210. https://doi.org/10.1137/0110015.
Laarhoven, P. J. M., and E. H. L. Aarts. 1987. Simulated Annealing: Theory and Applications. Kluwer Academic Publishers.
Nourani, Yaghout, and Bjarne Andresen. 1998. “A Comparison of Simulated Annealing Cooling Strategies.” Journal of Physics A: Mathematical and General 31 (41): 8373.
Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa