0% found this document useful (0 votes)
35 views24 pages

AI Lab - Garima

Uploaded by

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

AI Lab - Garima

Uploaded by

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

Title of the Report: Artificial Intelligence Lab Report

Submitted by: Garima Paudel

Submitted to: Prashant Paudel

Course Title: Artificial Intelligence

Date of Submission: 2/12/2024

Garima Paudel
Lab 1: To get familiar with SWI-Prolog and setting up the environment for implementing
algorithms.

Introduction:
SWI-Prolog is a free and open-source Prolog programming language implementation. Prolog is a
declarative programming language often used for symbolic reasoning and artificial intelligence
applications.

Task 1: Installing SWI-Prolog

a. Downloaded SWI-Prolog:
● First of all, we visited the official SWI-Prolog website
(https://www.swi-prolog.org/Download.html).

● Then we downloaded the appropriate version for our operating system


(Windows,macOS, or Linux).
b. Installed SWI-Prolog:
● We then followed the installation instructions provided on the website.
● Instructions were available for each O.S.
● For Windows, the installer was executed and followed the on-screen
instructions.
c. .Verified Installation:
To verify installation, we:
 Opened a command prompt or terminal.
 Typed swipland pressed Enter.
 If the SWI-Prolog interpreter starts without errors, the installation was
successful.
Task 2: Getting Started with SWI-Prolog

SWI-Prolog IDE:

 Launched the SWI-Prolog IDE.


 Familiarized ourselves with the interface (top menu, console, and tabs).

Garima Paudel
Hello World Program:

 Created a simple Prolog program to print "Hello, World!".


 Saved the file with a .pl
extension.
Run Prolog Program:

 Opened the saved Prolog file in SWI-Prolog.


 From the "File" menu, the "Consult..." option was used. This opened a file
dialog and the file was selected with a .pl extension.
 Or used command line:

?- consult('your_file.pl').

Garima Paudel
Lab 2: Study of PROLOG Programming language and its Functions. Write simple facts
for the statements using PROLOG.

Introduction

Prolog, which stands for "Programming in Logic," is a high-level programming language that is
associated with artificial intelligence and computational linguistics. Unlike imperative
languages such as C or Java, which specify how to perform tasks, Prolog is declarative,
focusing on what relationships and facts hold. It is particularly well-suited for tasks that involve
complex pattern matching, symbolic reasoning, and rule-based logic, such as natural language
processing, database management, and theorem proving. Prolog programs consist of a series of
rules and facts, and execution involves querying these rules to infer new information or solve
problems by logical deduction. Introduced in the 1970s by Alain Colmerauer and Robert
Kowalski, Prolog has since played a pivotal role in the development of logic programming and
remains a valuable tool in AI research and applications.

Basic Structure of Prolog

A Prolog program consists of facts, rules, and queries. The program's logic is definedthrough
the relationships between these elements.

Facts

Facts are statements about the world that Prolog understands to be true.

% Example facts

likes(john, pizza).
likes(mary, sushi).

Rules

Rules define relationships between facts. They consist of a head and a body.

Garima Paudel
% Example rule

friend(X, Y) :- likes(X, Z), likes(Y, Z).

Queries

Queries are questions posed to the knowledge base, seeking information.

% Example query

?- friend(john, mary).

Garima Paudel
Variables and Constants

Variables: Begin with an uppercase letter or an underscore. Represent unknown


values.

% Example variable
likes(john, X).

Constants: Represent known values.

% Example constant
likes(john, pizza).

History of Prolog

The heritage of prolog includes the research on theorem provers and some other automated
deduction system that were developed in 1960s and 1970s. The Inference mechanism of the
Prolog is based on Robinson’s Resolution Principle, that was proposed in 1965, and Answer
extracting mechanism by Green (1968). These ideas came together forcefully with the advent
of linear resolution procedures.

The explicit goal-directed linear resolution procedures, gave impetus to the development of a
general purpose logic programming system. The first Prolog was the Marseille Prolog based
on the work by Colmerauer in the year 1970. The manual of this Marseille Prolog interpreter
(Roussel, 1975) was the first detailed description of the Prolog language.

Prolog is also considered as a fourth generation programming language supporting the


declarative programming paradigm. The well-known Japanese Fifth-Generation Computer

Garima Paudel
Project, that was announced in 1981, adopted Prolog as a development language, and thereby
grabbed considerable attention on the language and its capabilities.

Applications of Prolog:

1. Natural Language Processing (NLP): Parsing and generating language constructs, syntactic
and semantic analysis.

2. Knowledge Representation and Reasoning: Modeling knowledge bases, ontologies, and


inference mechanisms.

3. Database Queries: Representing and executing complex data retrieval and manipulation.

4. Artificial Intelligence (AI) and Machine Learning (ML): Data set manipulation, decision
making, pattern recognition.

5. Constraint Solving: Representing variables, domains, and solving constraint satisfaction


problems.

6. Algorithm Implementation: Implementing algorithms for searching, sorting, and graph


theory applications.

7. Symbolic Computation: Manipulating symbols and expressions for algebraic manipulation


and automated reasoning.

Task

Given the following English statements:

● John is male.
● Jim is male.
● Tony is male.

● Eliza is female.
● Ann is female.

Garima Paudel
● Lisa is female.

● John is the parent of Jim.


● John is the parent of Ann.
● Eliza is the parent of Jim.
● Eliza is the parent of Ann.
● Ann is the parent of Peter.
● Ann is the parent of Lisa.
● Jim is the parent of Tony.

1. Express Statements in Prolog: Convert the provided English statements into a


Prolog Knowledge Base (KB) with appropriate predicates and facts.
2. Define Rules: Create Prolog rules to find the following relationships:
● Father
● Mother
● Grandparents
● Siblings

Solution:

male(john).
male(jim).
male(tony).

female(eliza).
female(ann).
female(lisa).

parent(john, jim).
parent(john, ann).
parent(eliza, jim).
parent(eliza, ann).
parent(ann, peter).

Garima Paudel
parent(ann, lisa).
parent(jim, tony).

father(X,Y) :- male(X), parent(X,Y).


mother(X,Y) :- female(X), parent(X,Y).
grandparent(X,Y) :- parent(X,Z) , parent(Z,Y).
siblings(X,Y) :- parent(A,X), parent(A,Y).

Garima Paudel
Lab 3: Write a program in PROLOG to implement a list and simple arithmetic.

Task A: List Operation (Finding length of list, sum of list, maximum value in list and
reversed list):

?- leng([2, 4, 6, 8, 10], Length).

?- sum([2, 4, 6, 8, 10], Sum).

?- max([2, 4, 6, 8, 10], Max).

?- reverse([2, 4, 6, 8, 10], Reversed).

Solution:

% Task 1: List Manipulation

% Finding the lenght of a list


leng([] , 0).
leng([_|Tail] , N) :- leng(Tail , N1) , N is N1 + 1.

% Summing the element of a list


sum([],0).
sum([Head|Tail], Total) :- sum(Tail, SumTail), Total is Head + SumTail.

% Finding the maximum element in a list


maximum([X], X).
maximum([Head|Tail], Max) :- maximum(Tail, MaxTail), Max is max(Head, MaxTail).

% Reversing a list
reverse(List, Reversed) :- reverseAcc(List, [], Reversed).
reverseAcc([], Acc, Acc).
reverseAcc([Head|Tail], Acc, Reversed) :- reverseAcc(Tail, [Head|Acc], Reversed).

Garima Paudel
Output:

Task B: Arithmetic Operation:

?- add(5, 3, Result).

?- subtract(10, 4, Result).

?- multiply(6, 2, Result).

?- divide(8, 2, Result).

Solution:

% Task 2: Simple Arithmetic Operations

Garima Paudel
% Addition
add(X, Y, Result) :- Result is X + Y.

% Subtraction
subtract(X, Y, Result) :- Result is X - Y.

% Multiplication
multiply(X, Y, Result) :- Result is X * Y.

% Division
divide(X, Y, Result) :- Result is X / Y.

Output:

Task C:
Given the following statements in the prolog:

% Products

product(apple, 50).

product(banana, 30).

product(grape, 25).

Garima Paudel
product(orange, 40).

% Suppliers

supplier(fruitSupplier, [apple, banana, grape, orange]).

supplier(citrusSupplier, [orange]).

% Prices

price(apple, 1.5).

price(banana, 0.8).

price(grape, 2.2).

price(orange, 1.0).

% Discounts

discount(apple, 0.2).

discount(banana, 0.1).

discount(grape, 0.3).

discount(orange, 0.15).

Create queries for following rules.

?- suppliedBy(fruitSupplier, ProductList).

?- totalCost(apple, Quantity, Cost).

=>

% Rule to find products supplied by a specific supplier

suppliedBy(Supplier, ProductList) :-

supplier(Supplier, Products),

findall(Product, (member(Product, Products), product(Product, _)), ProductList).

Garima Paudel
% Rule to calculate total cost for a specific product based on quantity and discounts

totalCost(Product, Quantity, Cost) :-

product(Product, Price),

discount(Product, Discount),

Cost is Quantity * (Price - (Price * Discount)).

Garima Paudel
Lab 4: Write a program in PROLOG to implement Depth First Search.

Theory:

• Depth-first search (DFS) is an uninformed search algorithm that helps traverse


a tree or graph using the concept of backtracking.

• This algorithm traverses all nodes by advancing along a specific path and uses
backtracking when it reaches the end of that path, allowing exploration of
alternative paths.

• The DFS approach uses a stack to facilitate its implementation.

Solution:

% Graph representation(adjacency list)


edge(a,b).
edge(a,c).
edge(b,d).
edge(c,e).
edge(c,f).
edge(d,g).
edge(e,h).

Garima Paudel
% Depth-first search
dfs(Node, Visited) :- dfs(Node, [], Visited).

dfs(Node, Path, Visited) :- \+ member(Node, Path), write(Node), n1, dfs_neighbours(Node,


[Node|Path], Neighbours), dfs_all(Neighbours, [Node|Path], Visited).

dfs_neighbours(Node, Path, Neighbours) :-


findall(NextNode, (edge(Node, NextNode), \+ member(NextNode, Path)), Neighbours).

dfs_all([],_,_).
dfs_all([H|T], Path, Visited) :- dfs(H, Path, Visited), dfs_all(T, Path, Visited).

Output:

Garima Paudel
Lab 5: Write a program in PROLOG to implement Breadth First Search.

Theory:

• The Breadth First Search (BFS) algorithm is used to search a graph data
structure for a node that meets a set of criteria.

• It starts at the root of the graph and visits all nodes at the current depth level
before moving on to the nodes at the next depth level.

• This is achieved very simply by using a FIFO queue, i.e., new successors go at end

• BFS uses a Queue to remember to get the next node to start a search when a
dead end occurs in any iteration

Solution:

% Graph representation (adjacency list)


edge(a, b).
edge(a, c).

Garima Paudel
edge(b, d).
edge(c, e).
edge(c, f).
edge(d, g).
edge(e, h).

% Breadth-first search
bfs(Start, Visited) :- bfs([Start], [], Visited).

bfs([], _, _).
bfs([Current|Rest], Path, Visited) :- \+ member(Current, Path), write(Current), nl,
bfs_neighbours(Current, [Current|Path], _, RestQueue), append(Rest, RestQueue,
NewQueue), bfs(NewQueue, [Current|Path], Visited).

bfs_neighbours(Node, Path, Neighbours, RestQueue) :-findall(NextNode, (edge(Node,


NextNode), \+ member(NextNode, Path)),Neighbours),subtract(Neighbours, Path,
RestQueue).

Output:

Garima Paudel
Garima Paudel
Lab 6: Write a program in PROLOG to implement A* Search.

• Pronounced as “A-star search”

• Idea: avoid expanding paths that are already expensive

• Evaluation function:

f(n) = g(n) + h(n)

• Where,

g(n) = cost so far to reach n (from start node)

h(n) = estimate cost from n to goal

f(n) = estimated total cost of path through n to goal

Algorithm

1. Create a Priority Queue.

2. Insert the starting node.

3. Remove a node from the priority queue.

3.1. Check if it is the goal node. If yes, then exit.

3.2. Otherwise, mark the node as visited and insert its neighbors into the priority
queue.

The priority of each node will be the sum of its cost from the start and the goal.

Garima Paudel
Solution:

% Graph representation (weighted directed graph)


edge(a, b, 2).
edge(a, c, 4).
edge(b, d, 3).
edge(c, e, 5).
edge(c, f, 1).
edge(d, g, 7).
edge(e, h, 6).

% Heuristic function (straight-line distance)


distance(a, h, 8).
distance(b, h, 6).
distance(c, h, 5).
distance(d, h, 7).
distance(e, h, 4).
distance(f, h, 3).
distance(g, h, 2).
distance(h, h, 0). % Distance from the goal to itself is 0.

% Goal state
goal(h).

Garima Paudel
% Node representation
% node(Current, F, G, Path)
% F: Total cost (G + H)
% G: Cost from the start node
% Path: Path from the start node to the current node
node(a, 0, 0, []).
node(b, 0, 0, []).
node(c, 0, 0, []).
node(d, 0, 0, []).
node(e, 0, 0, []).
node(f, 0, 0, []).
node(g, 0, 0, []).
node(h, 0, 0, []).

% A* search
a_star(Start, Path, Cost) :-
a_star([node(Start, 0, 0, [])], [], Path, Cost).
a_star([node(Current, _, G, Path)|_], _, Path, G) :-
goal(Current).
a_star([node(Current, _, G, Path)|Open], Closed, FinalPath, FinalCost)
:-
findall(node(Next, F, G1, [Current|Path]),
(edge(Current, Next, Cost), \+ member(Next, Closed),
G1 is G + Cost, heuristic(Next, H), F is G1 + H),
Successors),
append(Successors, Open, UpdatedOpen),
sort(UpdatedOpen, SortedOpen),
a_star(SortedOpen, [Current|Closed], FinalPath, FinalCost).
% Heuristic function (straight-line distance)
heuristic(Node, H) :- distance(Node, h, H).

Output:

Garima Paudel
Garima Paudel
Garima Paudel

You might also like