ai assignment 2
ai assignment 2
ai assignment 2
BSCS- 6th
Department of Computer Science, Bahria University, Lahore Campus
Assignment: [2] Due date: October 28, 2024
CODE:
INITIALIZATION:
import random
import math
import numpy as np
import networkx as nx
import time
import sys
import heapq
import matplotlib.pyplot as plt
import warnings
Display configurations
print("Configuration:")
print(f"Number of Cities: {NUM_CITIES}")
print(f"Map Dimensions: {MAP_WIDTH}km x {MAP_HEIGHT}km")
print(f"Number of Iterations: {NUM_ITERATIONS}")
print(f"Connections per City: {MIN_CONNECTIONS} to {MAX_CONNECTIONS}")
print(f"Distance Increase: {MIN_DISTANCE_INCREASE*100}% to
{MAX_DISTANCE_INCREASE*100}%")
print(f"Random Seed: {RANDOM_SEED}")
print("\nSearch Algorithms to be Implemented:")
for algo in SEARCH_ALGORITHMS:
print(f"- {algo}")
Map Generation
import networkx as nx
import random
import math
import numpy as np
return G
def generate_map():
"""
Generate a single map with cities and road distances.
"""
# 2.1 Generate random coordinates for cities
cities = generate_random_cities(NUM_CITIES, MAP_WIDTH, MAP_HEIGHT)
# 2.2 & 2.3 Ensure each city is connected to between 2 and 5 others and the
graph is fully connected
G = generate_fully_connected_graph(NUM_CITIES, MIN_CONNECTIONS,
MAX_CONNECTIONS)
return cities, G
cities, G = generate_map()
pos = cities
edge_labels = nx.get_edge_attributes(G, 'distance')
plt.figure(figsize=(10, 10))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=500,
edge_color='black')
nx.draw_networkx_edge_labels(G, pos, edge_labels={(u, v): f"{d['distance']:.1f}"
for u, v, d in G.edges(data=True)}, font_size=8)
plt.title("Randomly Generated Map of Cities")
plt.show()
import heapq
from collections import deque
while queue:
current = queue.popleft()
if current == goal:
break
for neighbor in graph.neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
parent[neighbor] = current
queue.append(neighbor)
# Reconstruct path
path = []
node = goal
while node is not None:
path.append(node)
node = parent.get(node)
path.reverse()
return path
while stack:
current = stack.pop()
if current == goal:
break
for neighbor in graph.neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
parent[neighbor] = current
stack.append(neighbor)
# Reconstruct path
path = []
node = goal
while node is not None:
path.append(node)
node = parent.get(node)
path.reverse()
return path
while heap:
cost, current, from_node = heapq.heappop(heap)
if current in visited:
continue
visited[current] = cost
parent[current] = from_node
if current == goal:
break
for neighbor in graph.neighbors(current):
if neighbor not in visited:
total_cost = cost + graph[current][neighbor]['distance']
heapq.heappush(heap, (total_cost, neighbor, current))
# Reconstruct path
path = []
node = goal
while node is not None:
path.append(node)
node = parent.get(node)
path.reverse()
return path
# Initialize frontiers
front_start = deque([start])
front_goal = deque([goal])
# Visited dictionaries
visited_start = {start: None}
visited_goal = {goal: None}
meeting_node = None
# Reconstruct path
path_start = []
node = meeting_node
while node is not None:
path_start.append(node)
node = visited_start[node]
path_start.reverse()
path_goal = []
node = visited_goal[meeting_node]
while node is not None:
path_goal.append(node)
node = visited_goal[node]
while heap:
_, current = heapq.heappop(heap)
if current == goal:
break
if current in visited:
continue
visited.add(current)
for neighbor in graph.neighbors(current):
if neighbor not in visited:
heapq.heappush(heap, (heuristic(neighbor, goal), neighbor))
if neighbor not in parent:
parent[neighbor] = current
# Reconstruct path
path = []
node = goal
while node is not None and node in parent:
path.append(node)
node = parent.get(node)
path.reverse()
return path
while heap:
f_cost, g_cost, current, from_node = heapq.heappop(heap)
if current in visited:
continue
visited[current] = g_cost
parent[current] = from_node
if current == goal:
break
for neighbor in graph.neighbors(current):
if neighbor not in visited:
edge_cost = graph[current][neighbor]['distance']
new_g_cost = g_cost + edge_cost
new_f_cost = new_g_cost + heuristic(neighbor, goal)
heapq.heappush(heap, (new_f_cost, new_g_cost, neighbor, current))
# Reconstruct path
path = []
node = goal
while node is not None:
path.append(node)
node = parent.get(node)
path.reverse()
return path
while True:
temp = dfs(start, goal, 0, threshold, path, visited)
if temp == 'FOUND':
return path
if temp == float('inf'):
return None # No path found
threshold = temp