0% found this document useful (0 votes)
25 views20 pages

Documentation

The document outlines the development of a Woldia City Navigation System using Prolog and Python, detailing the implementation of Dijkstra's algorithm for finding the shortest paths between cities. It includes edge definitions, bidirectional connection rules, and functions for calculating distances and paths in both Prolog and Python, utilizing the Flask framework and NetworkX library. The system allows users to find the shortest path and all possible paths between two cities, returning results in JSON format.

Uploaded by

Kedir Tahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views20 pages

Documentation

The document outlines the development of a Woldia City Navigation System using Prolog and Python, detailing the implementation of Dijkstra's algorithm for finding the shortest paths between cities. It includes edge definitions, bidirectional connection rules, and functions for calculating distances and paths in both Prolog and Python, utilizing the Flask framework and NetworkX library. The system allows users to find the shortest path and all possible paths between two cities, returning results in JSON format.

Uploaded by

Kedir Tahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

INTRODUCTION TO ARTIFICIAL INTELLIGENCE

EXPETR SYSTEM SYSTEM


WOLDIA CITY NAVIGATION SYSTEM USING PROLOG
AND PYTHON

Group 8
Prolog Woldia City Navigation System
• 1. Edge Definitions:
• define the weight(distance) in km
• 2. edge(adago, gonderber, 5).
• 3. edge(gonderber, menharya, 2).
• 4. edge(menharya, piasa, 6).
• 5. edge(piasa, hospital, 3).
• 6. edge(hospital, adago, 4).
• 7. edge(adago, medhanialem, 1).
• 8. edge(mogad, adago, 2).
• 9. edge(adago, menharya, 3).
• 10. edge(menharya, mebrathayl, 2).
• 11. edge(adago, maksegnogebeya, 2).
• o These lines define the roads (edges) between cities with a distance (weight)
associated with each road.
• o For example, the road from adago to gonderber has a distance of 5 KM.
Prolog Woldia City Navigation System
• 12. Bidirectional Connection Rule:
• 13. connected(X, Y, W) :- edge(X, Y, W).
• 14. connected(X, Y, W) :- edge(Y, X, W).
• o This ensures the roads are bidirectional. If there is a road from X
to Y with weight W, then Y to X is also connected with the same weight.
• 15. Dijkstra’s Algorithm – Shortest Path:
• 16. shortest_path(Start, End, Path, Distance) :-
• 17. dijkstra([[0, Start, []]], End, [], Path, Distance).
• o This is the main predicate that finds the shortest path between
Start and End.
• o It calls dijkstra/4 with an initial queue containing a distance of 0,
starting node Start, and an empty path list.
Prolog Woldia City Navigation System
• 18. Base Case of Dijkstra’s Algorithm:
• 19. dijkstra([[Distance, End, Path] | _], End, _, Path, Distance).
• o This is the base case for Dijkstra’s algorithm. If the destination (End) is reached, it returns the
accumulated Path and Distance.
• 20. Recursive Case of Dijkstra’s Algorithm:
• 21. dijkstra([[CurrentDist, CurrentNode, CurrentPath] | RestQueue], End, Visited, Path, Distance) :-
• 22. CurrentNode \== End,
• 23. findall(
• 24. [NewDist, NextNode, [NextNode | CurrentPath]],
• 25. (connected(CurrentNode, NextNode, W),
• 26. \+ member(NextNode, Visited),
• 27. NewDist is CurrentDist + W),
• 28. NextPaths
• 29. ),
• 30. append(RestQueue, NextPaths, NewQueue),
• 31. sort(NewQueue, SortedQueue),
• 32. dijkstra(SortedQueue, End, [CurrentNode | Visited], Path, Distance).
Prolog Woldia City Navigation System
• o This is the recursive case. It explores all the
neighbors (NextNode) of the CurrentNode (the node
currently being processed).
• o For each neighbor, it computes the new distance
(NewDist) and adds the neighbor to the path.
• o It adds the new paths to the queue (RestQueue),
sorts it (to prioritize the shortest paths), and continues
recursively.
Prolog Woldia City Navigation System
• 33. Find All Paths Between Two Cities:
• 34. all_paths(Start, End, Paths) :-
• 35. findall(Path, path(Start, End, [Start], Path), Paths).
• o This predicate finds all possible paths from Start to End.
• o It calls the path/4 predicate to generate each path.
• 36. Path Construction:
• 37. path(Node, Node, Acc, Path) :-
• 38. reverse(Acc, Path).
• o This is the base case for constructing a path. If the current node
is the same as the destination, it reverses the accumulated path
(Acc) to get the correct order from Start to End.
Prolog Woldia City Navigation System
• 44. Calculate the Distance of a Path:
• 45. path_distance([_], 0).
• o This is the base case for calculating the distance of a path. If the path
contains just one node (the destination), the distance is 0.
• 46. Recursive Path Distance Calculation:
• 47. path_distance([A, B | Rest], Distance) :-
• 48. connected(A, B, W),
• 49. path_distance([B | Rest], RestDistance),
• 50. Distance is W + RestDistance.
• • This is the recursive case. It calculates the distance between each pair of
consecutive nodes (A and B) and adds it to the distance of the remaining path
(RestDistance).
• • The total Distance is the sum of the current edge weight (W) and the distance
of the rest of the path.
Prolog Woldia City Navigation System

• 11. Find All Paths with Distances:


• 12. all_paths_with_distances(Start, End, Results) :-
• 13. all_paths(Start, End, Paths),
• 14. findall([Path, Distance], (member(Path, Paths),
path_distance(Path, Distance)), Results).
• • This predicate combines the previous ones. It first finds all
possible paths using all_paths/3 and then calculates the
distance for each path using path_distance/2.
• • It returns a list of pairs: each pair consists of a path and its
corresponding distance.
PYTHON CODE
• . from flask import Flask, render_template, request, jsonify
• • Explanation: This imports necessary modules from
the Flask framework.
• o Flask: The main class for creating a Flask web
application.
• o render_template: Used to render HTML templates
(e.g., for the homepage).
• o request: Used to handle HTTP requests, particularly
to access data sent via forms.
• o jsonify: A helper function to return JSON responses.
PYTHON CODE
• import networkx as nx
• • Explanation: This imports the networkx library and
gives it an alias nx. This library is used for working with
graphs, such as creating nodes and edges, and finding
paths between nodes.
• 3. app = Flask(__name__)
• • Explanation: Creates an instance of the Flask class.
The __name__ argument tells Flask to look for templates
and static files relative to the current file.
PYTHON CODE

• . G = nx.Graph()
• • Explanation: Creates an empty undirected graph G using NetworkX. This
graph will store nodes and edges that represent cities and their connections.
• 5. def load_network():
• • Explanation: Defines a function load_network() to populate the graph with
nodes and weighted edges representing different cities and connections between
them.
• 6-25. G.add_edge(...) statements inside load_network()
• • Explanation: Each G.add_edge() adds an edge between two cities
(represented as strings) in the graph. The weight argument defines the weight of
the edge, which could represent the distance or cost between two cities. The
add_edge function takes:
• o Two nodes (cities) as arguments.
• o A weight argument to define the cost/distance between them.
PYTHON CODE

• def find_shortest_path(start, end):


• • Explanation: Defines a function find_shortest_path() that
calculates the shortest path between two cities using Dijkstra’s
algorithm (since we're providing weights for the edges).
• 27. start = start.upper() and end = end.upper()
• • Explanation: Converts the input start and end cities to
uppercase to ensure case-insensitivity when searching the graph.
• 28-29. if start not in G.nodes or end not in G.nodes:
• • Explanation: Checks if the input cities exist in the graph. If
either city is not present, it returns None, None.
PYTHON CODE
• . path = nx.shortest_path(G, source=start, target=end,
weight='weight')
• • Explanation: Finds the shortest path between the start and
end cities using the nx.shortest_path() function. The
weight='weight' argument tells NetworkX to consider edge weights.
• 31. distance = nx.shortest_path_length(G, source=start,
target=end, weight='weight')
• • Explanation: Finds the total distance (or weight) of the
shortest path using nx.shortest_path_length().
• 32. return path, distance
• • Explanation: Returns the shortest path and its distance as a
tuple
PYTHON CODE
• except nx.NetworkXNoPath:
• • Explanation: If no path exists between the two cities
(i.e., a NetworkXNoPath exception occurs), it returns None,
None.
• 34. def find_all_paths(start, end):
• • Explanation: Defines a function find_all_paths() that
finds all possible paths between two cities, along with their
distances.
• 35. start = start.upper() and end = end.upper()
• • Explanation: Converts the input cities to uppercase for
PYTHON CODE

• if start not in G.nodes or end not in G.nodes:


• • Explanation: Checks if the cities exist in the graph. If
either does not exist, it returns None.
• 38. paths = list(nx.all_simple_paths(G, source=start,
target=end))
• • Explanation: Finds all possible simple paths (paths with
no repeated nodes) between the start and end cities using
nx.all_simple_paths().
• 39. path_distances = [...]
• • Explanation: Creates a list of tuples where each tuple
consists of a path and the sum of the weights (distances) of
PYTHON CODE
• return path_distances
• • Explanation: Returns a list of paths along with their
corresponding distances.
• 41. except nx.NetworkXNoPath:
• • Explanation: If no paths are found between the cities, it
returns None.
• 42. @app.route('/find_path', methods=['POST'])
• • Explanation: Defines a route for the POST method at the
URL /find_path. This route handles the submission of the form
(when the user submits the form with start and end cities).
PYTHON CODE
• def find_path():
• • Explanation: Defines the function to handle the /find_path
route. It processes the form data, finds the shortest path, and
returns a JSON response with the results.
• 44. start = request.form['start'] and end = request.form['end']
• • Explanation: Retrieves the start and end city values
submitted via the form.
• 45. path, distance = find_shortest_path(start, end)
• • Explanation: Calls the find_shortest_path() function to find
the shortest path and its distance between the two cities.
PYTHON CODE
• all_paths = find_all_paths(start, end)
Explanation: Calls find_all_paths() to get all possible paths between
the cities.
47. if path:
Explanation: Checks if a shortest path was found.
• 48. return jsonify({...})
• • Explanation: Returns a JSON response containing:
• o shortest_path: The shortest path found between the cities.
• o shortest_distance: The distance of the shortest path.
• o all_paths: A list of all possible paths and their distances.
• o If no paths are found, it returns an error message.
PYTHON CODE
• if __name__ == '__main__':
• • Explanation: This block checks if the script is being run
directly (not imported as a module).
• 54. load_network()
• • Explanation: Calls the load_network() function to
populate the graph with data when the app starts.
• 55. app.run(debug=False)
• • Explanation: Starts the Flask application. debug=False
means Flask will not display detailed error messages in the
browser during runtime.
PYTHON CODE
• else: return jsonify({'error': 'No path found between the cities.'})
• • Explanation: If no path was found, it returns a JSON error
message.
• 50. @app.route('/')
• • Explanation: Defines a route for the homepage (URL /) to
render the main HTML template.
• 51. def index():
• • Explanation: Defines the function to handle the / route and
render the homepage.
• 52. return render_template('index.html')
• • Explanation: Renders the index.html template (the homepage)
when the root route is accessed.

You might also like