Artificial intellegence lab manual

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 149

MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY

S.Z.A.B CAMPUS KHAIRPUR MIR’S,


Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence
Practical No. 01
Topic:Introduction to Neural Network
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: _____________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

Deep Neural Network:

A deep neural network is a neural network with a certain level of complexity, a


neural network with more than two layers. Deep neural networks use sophisticated
mathematical modelling to process data in complex ways.
Fuzzy Logic
Fuzzy logic is designed to solve problems by considering all available information
and making the best possible decision given the input.

The term fuzzy refers to things that are not clear or are vague. In the real world
many times we encounter a situation when we can’t determine whether the state
is true or false, their fuzzy logic provides very valuable flexibility for reasoning.
In this way, we can consider the inaccuracies and uncertainties of any situation.

In the boolean system truth value, 1.0 represents the absolute truth value and 0.0
represents the absolute false value. But in the fuzzy system, there is no logic for
the absolute truth and absolute false value. But in fuzzy logic, there is an
intermediate value too present which is partially true and partially false.
Reinforcement learning
Reinforcement learning is the training of machine learning models to make a
sequence of decisions. The agent learns to achieve a goal in an uncertain,
potentially complex environment. In reinforcement learning, an artificial
intelligence faces a game-like situation. The computer employs trial and error to
come up with a solution to the problem. To get the machine to do what the
programmer wants, the artificial intelligence gets either rewards or penalties for the
actions it performs. Its goal is to maximize the total reward.
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4th Year

Artificial Intelligence

Practical No. 2
Topic: Learning MATLAB Neural Networks toolbox for the
development of neural network-based applications.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: ____________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING /RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand Artificial Neural Network.
 Understand Working of Neural Networks toolbox.
 Create a perceptron network to perform the operation of AND function and OR function.

 EQUIPMENT & Tool:


 personal computer (PC)
 MATLAB

Artificial Neural Network


 An artificial neuron network (ANN) is a computational model based on the structure and
functions of biological neural networks.
 ANN is a computational model to simulate human brain behavior.
 ANN is designed to simulate the way the human brain analyzes and processes information.
 ANN has self-learning capabilities that enable them to produce better results as more data
become available
McCulloch Pits Model
 McCulloch Pits model is the model of first artificial neural network.
 McCulloch & Pitts (1943) are generally recognized as the designers of the first artificial neural
network.

Figure 1 Artificial Neuron

 McCulloch-Pitts Model is a Boolean circuit model of brain.


 It may be divided into 2 parts. The first part, g takes an input performs an aggregation and
based on the aggregated value the second part, f makes a decision.
 Mathematically

We can see that g(x) is just doing a sum of the inputs — a simple aggregation. And theta here is
called thresholding parameter. Each neuron has a fixed threshold. If the net input into the
neuron is greater than or equal to the threshold, the neuron fires. Inputs & output — are only
Boolean. The activation of a neuron is binary. That is, the neuron either fires (activation of one)
or does not fire (activation of zero).

Neural Network Toolbox

Neural networks are adjusted, or trained, so that a particular input leads to aspecific target
output. This lab session gives you an insight of training a neural network to fita function
using Neural Network Toolbox functions.

 Perceptron
A perceptron is a simple model of a biological neuron in an artificial neural network. Perceptron is
also the name of an early algorithm for supervised learning of binary classifiers.

 Creating perceptron network to perform the operation of AND function.

We will first create a perceptron network to perform the operation of AND function for
twovariables.To start neural network toolbox type nntool. The following window appears see
figure 1
Figure 2

First, define the network input, called p, having the value [0 0 1 1;0 1 0 1]. Thus, thenetwork has a
two-element input, and four sets of such two-element vectors are presented to itin training. To
define this data, click New, and a new window, Create Network or Data,appears (see figure 2).
Select the Data tab. Set the Name to p, the Value to [0 0 1 1; 0 10 1], and set Data Type to Inputs.

Figure 3 Figure 4

Click Create and then click OK to create an input p. The Network/Data Manager window appears,
and p shows as an input. Next create a network target. This time enter the variable name t, specify
the value [0 0 0 1], and click Targets under Data Type. Again click Create and OK (See figure
3).You will see in the resulting Network/Data Manager window that you now have t as a target as
well as the previous p as an input. In order to create a new network ANDNet, select the Network
tab. Enter ANDNetunder Name. Set the Network Type to Perceptron, for that is the kind of
network you want to create. You can set the inputs to p, and the example targets to t. You can use a
hardlimtransfer function with the output range [0, 1] that matches the target values and a
learnplearning function. For the Transfer function, select hardlim. For the Learning
function,selectlearnp. The Create Network or Data window now looks like the following figure (see
figure 4)

Figure 5

Now click Create and OK to generate the network. Now close the Create Network or Data
window. To train the network, click ANDNet to highlight it (see figure 5).
Figure 6

Then double click to Open. This leads to a new window, labeled Network: ANDNet. (see Figure 6)

Figure 7

At this point you can see the network again by clicking the View tab. You can also check on the
initialization by clicking the Initialize tab. Now click the Train tab. specify the inputs and output by
clicking the Training Info tab and selecting p from the list of inputs and t from the list of targets.
The Network: ANDNet window should look like figure 7.
Figure 8

At this stage, if you want to view what weight values have been assigned or edit the values, you can
do this by clicking on View/Edit Weights. You can also initialize weights again by clicking on
Reinitialize Weights tab.
Click Train Network to train the perceptron network. The following training results
appear (see figure 8).
Figure 9

The network was trained to zero error in five epochs. Confirm that the trained network does indeed
give zero error by using the input p and simulating the network. To do this, go to the Network:
ANDNetwindow and click the Simulate tab. Use the Inputs menu to specify p as the input, and
label the output as ANDNet_outputsSim to distinguish it from the training output. (See Figure 9).
Click Simulate Network in the lower right corner and click OK. In the Network/Data Manager
you see a new variable in the output: ANDNet_outputsSim(See Figure 10). Double-click it and a
small window, Data: ANDNet_outputsSim, appears with the value [0 0 0 1]. Compare with training
Data: ANDNet_outputs(See Figure 11)..Thus, the network does perform the AND of the inputs,
giving a 1 as an output only in this last case, when both inputs are 1.
Figure 10

Figure 11 Figure 12

Lab Exercise

1. Develop perceptron network to perform operation of OR function. Write the value of


inputand output. Also mention the learning function that you used and in how many
epochs yournetwork is trained to zero error. Attach screen shots of training window.

Step: 01
 Write “nntool” in command window we get.
Step: 02
Creating Input and Target.

Step: 03
Creating Network.
Step: 04
Labelled Network.
Step: 05
Training Network.

Step: 06
Simulating Network.
Step: 07
Results.

Conclusion:
Have you become familiar with MATLAB Neural Networks toolbox? What concepts did
you gain from this practical? Comment

I have become familiar with the MATLAB Neural Network toolbox components and its
command; in this toolbox we can design different types of logic gates. its real times
applications.
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence
Practical No. 3
Topic:Generating and processing undirected and directed graphs
using MATLAB.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: _____________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand graphs i.e directed and undirected graphs.
 Create directed and undirected graphs using MATLAB.
 Find shortest path in a graph using MATLAB.

 EQUIPMENT & Tool:


 personal computer (PC)
 MATLAB

Graph
A graph is a pictorial representation of a set of objects where some pairs of objects are connected
by links. The interconnected objects are represented by points termed as vertices, and the links that
connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices (Nodes) and E is the set of
edges, connecting the pairs of vertices.
In the below graph, V = {a, b, c, d, e} and E = {ab, ac, bd, cd, de}.
Figure 13 Graph

Undirected & Directed Graph


Undirected graphs have edges that do not have a direction. The edges indicate a two-way
relationship, in that each edge can be traversed in both directions. Directed graphs have edges with
direction. The edges indicate a one-way relationship, in that each edge can only be traversed in a
single direction.

Weighted graph
A graph in which each of the edge is associated with a real number (weight) is called as weighted
graph. Both undirected and directed graphs can be weighted.

Creating undirected & Directed Graphs in MATLAB

 Undirected graphs in MATLAB


In MATLAB we can generate a undirected graph with the help of graph() function. Consider the
following undirected graph:

Example 1

Nodes: Edges: Weights:


A=1 AB = {1,2} AB = 10
B=2 AC = {1,3} AC = 5
C=3 BD = {2,4} BD = 2
D=4 BE = {2,5} BE = 9
E=5 CD = {3,4} CD = 8
F=6 DF = {4,6} DF = 3
EF = {5,6} EF = 6

Where s is the vector containing first node of each of the edge and t is the vector containing second
node of each of the edge. As this is undirected graph so, edge AC is same as CA.

Example 2

Nodes: Edges: Weights:


A=1 AB = {1,2} AB = 5
B=2 AC = {1,3} AC = 4
C=3 BC = {2,3} BC = 2

 Directed graphs in MATLAB


In MATLAB we can generate a directed graph with the help of digraph() function. Consider the
following directed graph:
Example 1
Nodes: Edges: Weights:
A=1 AC = {1,3} AC = 10
B=2 BA = {2,1} BA = 5
C=3 BE = {2,5} BE = 2
D=4 CD = {3,4} CD = 9
E=5 DB = {4,2} DB = 8
F=6 DF = {4,6} DF = 3
FE = {6,5} FE = 6

Shortest Path
The shortest path is a path between two vertices (or nodes) in a graph such that the sum of the
weights of its constituent edges is minimized. Consider the following graph:

There are 4 paths from Node A to F


Path 1 = A → C → D → F (Sum of weights = 10 + 9 + 3 = 22)
Path 2 = A → C → D → B → F (Sum of weights = 10 + 9 + 8 + 2 = 29)
Path 3 = A → D → F (Sum of weights = 3 + 3 = 6)
Path 4 = A → D → B → F (Sum of weights = 3 + 8 + 2 = 11)
Path 3 is the shortest path between the nodes A and F because the sum of weights of constituent
edges is smallest.
In MATLAB we can use shortestpath() functions to find the shortest path between two nodes. It
takes three arguments: graph in which to find the shortest path and two nodes. Below MATLAB
code finds and highlights the shortest path between the nodes A and F:

Example 1

Nodes: Edges: Weights:


A=1 AC = {1,3} AC = 10
B=2 AD = {1,4} AD = 3
C=3 BA = {2,1} BA = 5
D=4 BE = {2,5} BE = 2
E=5 BF = {2,6} BF = 2
F=6 CD = {3,4} CD =9
DB = {4,2} DB = 8
DF = {4,6} DF = 3
FE = {6,5} FE = 6

 Shortest Path b/w cities

Procedure
Consider the following city map directed graph, where weight of each edge represent the distance
between two cities in kilometers:
Step 01: Identify the nodes and number them:
1 – Karachi, 2 – Jamshoro, 3 – Hyderabad, 4 – Nawabshah, 5 – Khairpur
Step 02: Identify the edges and their weights:
{1,2}=150, {1,3}=162, {2,1}=150, {2,3}=16, {3,1}=162, {3,2}=16, {3,4}=124,
{4,2}=128, {4,3}=124, {4,5}=163, {5,2}=300, {5,4}=163
Step 03: Open MATLAB and create new script file.
Step 04: Write down the below code in script file:
Where s is the vector containing first node of each of the edge and t is the vector containing second
node of each of the edge.

Step 05:Press Run button to execute the script.

Step 06: Now find the shortest path between nodes Karachi to Nawabshahby appending below
two commands and re-run the script:

Lab Exercise
1. Define the following terms:
a. Regular Graph
b. Null Graph
c. Trivial Graph
d. Simple Graph
e. Connected Graph
f. Disconnected Graph
g. Complete Graph
h. Cyclic Graph
i. Degree of vertex
j. Pendent Vertex
k. Loop
l. Parallel Edges

2. Consider the following undirected graph:


a) Create and plot the graph in MATLAB.
b) Display the shortest path and distance between nodes B and C.
c) Display the edge with minimum weight (Hint: use min() function, G.Edges and G.Edges.Weights).
d) Display the edge with maximum weight.
e) Display all the neighboring nodes of node E (Hint: use neighbors() function).

3. Consider the following city map graph:

a) Create and plot the graph in MATLAB.


b) Display and highlight the shortest path and distance between HALA and KHAIRPUR.
c) Display and highlight the shortest path and distance between NAWABSHAH and KOTRI.
d) Display all the cities which are inside 140 km radius of JAMSHORO (Hint: use nearest() function).

4) Consider the following directed graph:

a) Create and plot the graph in MATLAB.


b) Display and highlight the shortest path and distance between nodes A and G.
c) Display all the nodes which are inside 50 units radius of node C.

Conclusion:

Have you become familiar with graphs in MATLAB? What concepts did you gain from this practical
about directed and undirected graph in MATLAB? Comment
I have become familiar with the directed and undirected graphs and their applications
and in path finding.

References:
https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html
https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html#bur8goj
https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html#bur8om2
https://www.mathworks.com/help/matlab/ref/digraph.html
https://www.mathworks.com/help/matlab/ref/graph.shortestpath.html
The End
Lab 3

Task 1

(a)

(b)
(C) (d)

(e)
Task 2

(a)
Task 3
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY

S.Z.A.B CAMPUS KHAIRPUR MIR’S,


Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 4
Topic:Breadth First Search (BFS) algorithm using MATLAB
Student’s Roll no:K18ES15 Points Scored: __________________________

Date of Conduct: ________________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT
 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand Breadth first Search (bfs) Algorithm.
 Understand Working of bfsearchfunction in MATLAB.
 Apply Breadth first Search (bfs) Algorithm on directed and undirected graphs.

 EQUIPMENT & Tool:


2. personal computer (PC)
3. MATLAB

Breadth First Search (BFS) algorithm

 Breadth First Search


Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures.
It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a search key)
and explores the neighbor nodes first, before moving to the next level neighbors.

Figure 14 BFS

 Breadth First Search (BFS) algorithm


Graphs may contain cycles, so we may come to the same node again. To avoid processing a node
more than once, we use a Boolean visited array. It uses a queue to mark the visited nodes so that
they should not be repeated again.

[1] Step 1: Choose some starting vertex (node) and insert it in queue.
[2] Step 2: Visit adjacent unvisited vertex. Mark it visited. Display it. Insert it in a queue.
[3] Step 3: If no adjacent vertex found, remove the first vertex from queue.
[4] Step 4: Repeat Rule 2 and Rule 3 until queue is empty.

Breadth First Search using MATLAB


The bfsearch function in MATLAB is used to perform breadth-first graph search. The syntax for
bfsearch function is given below:

v = bfsearch(G,s)

v = bfsearch(G,s) applies breadth-first search to graph G starting at node s. The result is a vector of
node IDs in order of their discovery..

 Example
s = [1 1 1 1 2 2 2 2 2 2 2 2 2 2 15 15 15 15 15];
t = [3 5 4 2 14 6 11 12 13 10 7 9 8 15 16 17 19 18 20];
G = graph(s,t);
plot(G)
v = bfsearch(G,2)
Also try for v = bfsearch(G,1) , what is Difference _ ?

Lab Exercise

 Consider the following directed graph


a. Apply Breadth-First Search and write down state of Queue, Visited Nodes and Current Node in
each step, consider 1 is the starting node.
b. Use bfsearch() function to verify your answer at every step.

 Consider the following undirected graph

a. Apply Breadth-First Search and write down state of Queue, Visited Nodes and Current Node in
each step, consider A is the starting node.
b. Use bfsearch() function to verify your answer at every step.

 Consider the following undirected graph


a. Apply Breadth-First Search and write down state of Queue, Visited Nodes and Current node in
each step, consider A is the starting node.
b. Use bfsearch() function to verify your answer at every step,
c. Apply Breadth-First Search and write down state of Queue, Visited Nodes and Current node in
each step, consider J is the starting node.

Conclusion:

Have you become familiar Breadth First Search (BFS) algorithm using MATLAB? What concepts did
you gain from this practical? Comment
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____

References:
https://www.mathworks.com/help/matlab/ref/graph.bfsearch.html
https://www.mathworks.com/help/matlab/ref/graph.bfsearch.html#butxivb-5
https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/tutorial/
https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/

The End
LAB 4

Example 1

Result:

Example 2.1:
Task1

Current Queue Visited

1 --- 1
1 2 12
1 7 2 de queue 127
2 7 127
2 37 1273
2 4 3 7 de queue 12734
7 43 12734
7 8 4 3 de queue 127348

3 8 4de queue 127348


4 8 127348
4 58 1273485
4 6 5 8 de queue 12734856
8 65 12734856
8 9 6 5 De queue 127348569
5 9 6 de queue 127348569
6 9 de queue 127348569
9 --- 127348569

Task 2

Task 3

Code:
Result:
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY

S.Z.A.B CAMPUS KHAIRPUR MIR’S,


Department of Electronic Engineering
8th Semester 4th Year

Artificial Intelligence

Practical No. 5
Topic:Depth First Search (DFS) algorithm using MATLAB.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: ________________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand Depth first Search (dfs) Algorithm.
 Understand Working of dfsearchfunction in MATLAB.
 Apply Depth first Search (dfs) Algorithm on directed and undirected graphs.

EQUIPMENT & Tool:


 personal computer (PC)
 MATLAB

Depth First Search (DFS) algorithm


 Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data
structures. One starts at the root (selecting some arbitrary node as the far as possible along
each branch before backtracking. Depth First Search algorithm (DFS) traverses a graph in a
depth ward motion and uses a stack to remember to get the next vertex to start a search when a
dead end occurs in any iteration.
 A depth first search begins at the root node (i.e. Initial node) and works downward to
successively deeper levels.
 One starts at the root and explores as far as possible along each branch before backtracking.
 Uses a LIFO STACK.

Figure 15 DFS

 Depth First Search (DFS) algorithm


[5] Step 01: Choose the starting node, mark it as visited, push it on Stack and make it current
node.
[6] Step 02: Find adjacent unvisited node of current node, push it on Stack, mark it visited and
make it current node.
[7] Step 03: If no unvisited adjacent node found, pop out node from Stack and make top of the
stack as current node.
[8] Step 04: Repeat Step 02 to Step 03 until Stack is empty

Depth First Search using MATLAB

The dfsearch function in MATLAB is used to perform depth-first graph search. The syntax
for dfsearch function is given below:

v = dfsearch(G,s) v = dfsearch(G,s) applies depth-first search to graph G starting at node s


and returns the node indices in order of discovery.

4. Example
s = [1 1 1 1 2 2 2 2 2 2 2 2 2 2 15 15 15 15 15];
t = [3 5 4 2 14 6 11 12 13 10 7 9 8 15 16 17 19 18 20];
G = graph(s,t);
plot(G)
v = dfsearch(G,1)
Also try for v = dfsearch(G,2) , what is Difference _ ?
Lab Exercise

 Consider the following directed graph

 Apply Depth-First Search and write down state of Stack, Visited Nodes and Current Node in
each step, consider 1 is the starting node.
 Use dfsearch() function to verify your answer at every step.

 Consider the following undirected graph


1. Apply Depth-First Search and write down state of Stack, Visited Nodes and Current Node in
each step, consider A is the starting node.
2. Use dfsearch() function to verify your answer at every step.

 Consider the following undirected graph

a) Apply Depth-First Search and write down state of Stack, Visited Nodes and Current node in
each step, consider A is the starting node.
b) Use dfsearch() function to verify your answer at every step,

5. Conclusion:

Have you become familiar with Depth First Search (DFS) algorithm using MATLAB? What
concepts did you gain from this practical? Comment
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____

References:
https://www.interviewcake.com/concept/java/dfs
https://www.mathworks.com/help/matlab/ref/graph.dfsearch.html
https://gjacopo.github.io/imtools/graph/dfs.html

The End
Lab 5

Task 1

Task 2
Task 3

Result:
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronics Engineering
8th Semester 4th Year

Artificial Intelligence
Practical No. 6
Topic: Learning MATLAB Fuzzy Logic toolbox for or analyzing, designing,
and simulating systems based on fuzzy logic.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: _____________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

[9] OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand Fuzzy logic.
 Become familiar with MATLAB Fuzzy Logic toolbox.
 Design and simulate systems based on Fuzzy Logic.

EQUIPMENT & TOOL:


 personal computer (PC)
 MATLAB

Fuzzy Logic
3. Fuzzy logic is a form of many-valued logic in which the truth values of variables may be any real
number between 0 and 1 both inclusive. It is employed to handle the concept of partial truth,
where the truth value may range between completely true and completely false. By contrast, in
Boolean logic, the truth values of variables may only be the integer values 0 or 1.
4. The idea of fuzzy logic was first advanced by Dr. LotfiZadeh of the University of California at
Berkeley in the 1960s.
Fuzzy Logic Toolbox in MATLAB
Fuzzy Logic Toolbox™ provides functions, apps, and a Simulink® block for analyzing, designing, and
simulating systems based on fuzzy logic. The product guides you through the steps of designing
fuzzy inference systems. Functions are provided for many common methods, including fuzzy
clustering and adaptive neurofuzzy learning. The toolbox lets you model complex system behaviors
using simple logic rules, and then implements these rules in a fuzzy inference system. You can use it
as a stand-alone fuzzy inference engine. Alternatively, you can use fuzzy inference blocks in
Simulink and simulate the fuzzy systems within a comprehensive model of the entire dynamic
system.

Fuzzy Logic Model “Washing Machine” Case study

Using Fuzzy Logic Toolbox MATLAB


 Introduction

Fuzzy logic washing machines are gaining popularity. These machines offer the advantages of
performance, productivity, simplicity and less cost. Sensors continually monitor varying conditions
inside the machine and accordingly adjust operations for the best wash results. The fuzzy logic
checks for the extent of dirt and grease, the amount of soap and water to add, direction of spin, and
so on. The machine rebalances washing load to ensure correct spinning. Neuro fuzzy logic
incorporates optical sensors to sense the dirt in water and a fabric sensor to detect the type of
fabric and accordingly adjust wash cycle.

 General Diagram: Fuzzy Logic Model “Washing Machine”

To model a system using fuzzy logic, the first step is to determine the inputs and outputs of it. A
washing machine’s most important duty is to clean the cloths without damaging them. In order to
achieve it, the output parameters of fuzzy logic, which are related to washing, must be paid
importance. Inputs and outputs of fuzzy logic system are shown in figure given below.

Fuzzy Logic
Input Variables 1.Type Model
of Dirt 2.Type of Cloth Output Variable
3.Dirtiness of Cloth Wash Time
"WashingMachine"

Input Output

Figure 16 Fuzzy Logic System "Washing Machine"


 Implementation of Fuzzy Logic Model “Washing Machine” in Fuzzy Logic Toolbox

 To implement Fuzzy Logic System “Washing Machine” follow steps are followed:

 Define Linguistic Inputs and Linguistic output

Here Linguistic inputs and Linguistic output are Linguistic Variables.


Linguistic Variables: Humans normally use different words to represent the degree of truthness of
some quantity or quality.
– Speed: {slowest, slow, fast, fastest}
– Temperature: {freezing, cool, warm, hot}
– Cloud Cover: {overcast, partly cloudy, sunny}

Figure 17 Linguistic Inputs and Linguistic Output


 Define inputs in Fuzzy Logic Designer
 Write on command window “fuzzy” and new window for fuzzy logic designer will appear.

 We have to define all three inputs by adding variables for input.

 After adding input variables, fuzzy logic designer will look like this.

 Give name to the input variables i.e. 1. Type of cloth, 2. Type of dirt, 3. Dirtiness of cloth.
 Define Output variable in Fuzzy Logic Designer
 As already in fuzzy logic designer we have one output this is desired for our fuzzy logic system
“washing machine” so we just rename it as wash time.

 Add membership functions for each input variable, see figure 2 for details.
 Double click on any input a new window for Membership functions will be opened.
 For Type of cloth are defined in silk, Woolen, Cotton. Note Specify range also that is 0-100 as
shown in diagrams below

 Add membership functions for type of dirt i.e. non gressy , medium and gressy and specify
range 0-100 .
 Add membership functions for dirtiness of cloth i.e. small, medium and large and specify range
0-100.

 Add membership functions for output variable, see figure 2 for details.
 1st remove all MIF’s for output variable and then add custom MIF that are 5. Also Define display
range and range 0-100.

 Now define these custom 5 MIF’s that are very short, short, medium, long and very long.
Also add parameters range for each membership function of output variable.

i.e. for very short [-25 0 15] , short [15 25 35], medium [30 50 60], long [60 75 80] and for very long
[85 100 125] should be defined as parameters .

 Modify Rules for Fuzzy Logic Model “Washing Machine”


 Double click on Rule Editor a new window for rule editor will open.
 Add rules, refer diagram 2 for details. Following rules should be added.

1. If (Type_of_cloth is Silk) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is small) then


(Wash_Time is very_short) (1)
2. If (Type_of_cloth is Silk) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is short) (1)
3. If (Type_of_cloth is Silk) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is large) then
(Wash_Time is medium) (1)
4. If (Type_of_cloth is Silk) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is small) then
(Wash_Time is medium) (1)
5. If (Type_of_cloth is Silk) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is long) (1)
6. If (Type_of_cloth is Silk) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is large) then
(Wash_Time is long) (1)
7. If (Type_of_cloth is Silk) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is small) then
(Wash_Time is medium) (1)
8. If (Type_of_cloth is Silk) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is long) (1)
9. If (Type_of_cloth is Silk) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is large) then
(Wash_Time is very_long) (1)
10. If (Type_of_cloth is woolen) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is small) then
(Wash_Time is short) (1)
11. If (Type_of_cloth is woolen) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is medium)
then (Wash_Time is medium) (1)
12. If (Type_of_cloth is woolen) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is large) then
(Wash_Time is long) (1)
13. If (Type_of_cloth is woolen) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is small) then
(Wash_Time is medium) (1)
14. If (Type_of_cloth is woolen) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is medium) (1)
15. If (Type_of_cloth is woolen) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is large) then
(Wash_Time is long) (1)
16. If (Type_of_cloth is woolen) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is small) then
(Wash_Time is long) (1)
17. If (Type_of_cloth is woolen) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is long) (1)
18. If (Type_of_cloth is woolen) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is large) then
(Wash_Time is very_long) (1)
19. If (Type_of_cloth is cotton) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is small) then
(Wash_Time is short) (1)
20. If (Type_of_cloth is cotton) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is medium)
then (Wash_Time is medium) (1)
21. If (Type_of_cloth is cotton) and (Type_of_Dirt is non_gressy) and (Dirtiness_of_Cloth is large) then
(Wash_Time is long) (1)
22. If (Type_of_cloth is cotton) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is small) then
(Wash_Time is medium) (1)
23. If (Type_of_cloth is cotton) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is long) (1)
24. If (Type_of_cloth is cotton) and (Type_of_Dirt is medium) and (Dirtiness_of_Cloth is large) then
(Wash_Time is very_long) (1)
25. If (Type_of_cloth is cotton) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is small) then
(Wash_Time is long) (1)
26. If (Type_of_cloth is cotton) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is medium) then
(Wash_Time is long) (1)
27. If (Type_of_cloth is cotton) and (Type_of_Dirt is gressy) and (Dirtiness_of_Cloth is large) then
(Wash_Time is very_long) (1)

- All 27 rules are added in rule editor.

 To view rules, go to view rules and a window known as rule viewer will appear.
 For different input variables wash time will be different. Fuzzy rules have been established
for the modeling of washing machine. The whole system has been developed by using
MATLAB’s fuzzy logic toolbox.

 Final fuzzy logic Model “Washing Machine” surface view.


 The results of above rules, which have been determined by applying Min-Max operator, are
illustrated in the form of 3D graphs in figures given below.
These figures show the relationship between input and output parameters.
 To view Surface, click on view and then surface, a new window of surface view will appear.
Lab Exercise

6. Consider the same case study of washing machine; create a fuzzy logic model “Washing
Machine” by using fuzzy logic toolbox MATLAB with some more input, output variables and
rules. Attach all steps screenshots.
Task:
Step 01: Fuzzy logic designer with three inputs and one output.
Step: 02 Setting Cloth-type and its parameters.
Step: 03 Setting Dirt-type and its parameters.
Step: 04 Setting Degree of Dirtiness and its parameters.
Step: 05 Setting Output and its parameters.
Step: 06 writing up Rules for Fuzzy logic different parameters.
Step: 07 Surface View.
Step: 08 Final result in 3D.

Conclusion:

Have you become familiar Fuzzy Logic Toolbox in MATLAB? What concepts did you gain
from this practical? Comment
I have become familiar with Fuzzy Logic Toolbox in MATLAB, it is one of the best
techniques that can be used in data handling output prediction than the old
technique that gives only two results High or low on the other hand we have Fuzzy
Logic that always enables us to give intermediate results as well, in MATLAB we
can analyze our results using surface as well as in 3D graph.
References:
https://www.youtube.com/watch?v=K3K8OH61pRg
https://www.mathworks.com/products/fuzzy-logic.html

The End
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY

S.Z.A.B CAMPUS KHAIRPUR MIR’S,


Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 7
Topic:Getting Familiar with visual PROLOG.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: ________________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand visual PROLOG environment.
 Understand basic concepts of visual Prolog.
 Create simple programs using visual Prolog.

 EQUIPMENT & Tool:


 personal computer (PC)
 visual PROLOG

Introduction
There are two types of programming languages: Procedural and Declarative. Procedural languages
are used to perform numerical computations like: Computing area of a circle, finding percentage
marks of a student, finding the person with greater age. All these problems involve some sort of
numerical computations (formulae). Some of the procedural programming languages are: C/C++,
JAVA, C#, BASIC FORTRAN etc. Whereas declarative languages are used to perform non-numerical
computations like: who is the mother of John? Finding all the students who like AI? Are John and
Tom brothers? Now all these problems involve non-numeric computations there is no formula to
find out who is the mother of John? you do not have any formula to conclude which students like AI;
you do not have formula to tell whether John and Tom are brothers of each other. These types of
problems cannot be solved by traditional procedural languages. Some of the declarative
programming languages are: PROLOG (Programming in Logic), LISP (List Processing) and ML (Meta
Language).

Visual PROLOG
 Download visual PROLOG
https://www.visual-prolog.com/vip/download/default.htm
 What is PROLOG?

PROLOG stands for PROgramming in LOGic. Prolog is a high-level declarative programming


language for symbolic and non-numeric computation. It is especially well suited for solving
problems that involve objects and relations between objects.Figure 1 shows an example: a family
relation. The fact that Tom is a parent of Bob can be written in Prolog as:

Pam Tom

Bob Liz

Ann Pat
Jim

Figure 18 Family Tree

Here we choose parent as the name of a relation; tom and bob are its arguments.
For reasons that will become clear later we write names like tom with an initial lower-case letter.
The whole family tree of Figure 1 is defined by the following Prolog program:
parent(“pam”, “bob”).
Parent (“tom”, “bob”).
Parent(“tom”, “liz”).
parent(“bob”, “ann”).
parent(“bob”, “pat”).
Parent (“pat”, “jim”).
Basic elements of PROLOG (Facts, Rules and Questions)
Prolog programs are composed of declarative sentences to be asserted. These sentences are called
predicates. These predicates are of two types: Facts and Rules.

 Facts

Facts are the declarative sentences which are always true. Facts can represent either relationships
between objects or properties of objects. For example:

o Syntax of Fact

Predicate (arg1, arg2, arg3, . . . ,argN).

 Rules

Rules are the declarative sentences which depend on one or more other facts being true.

Example 1:Person1 is mother of Person2 if Person1 is female and Person1 is parent of person2.
mother(Person1, Person2) :- female(Person1) , parent(Person1,Person2).
Example 2:Person1 is friend of Person2 if Person1 knows Person2 and Person1 likes Person2.
friend(Person1, Person2) :- knows(Person1, Person2) , likes(Person1, Person2).

Example 3:A mobile is off if it is out of battery or it is shutdown.


off(mobile) :- outofbattery(mobile) ;shutdown(mobile).

o Syntax of Fact

predicate1(arg1, arg2, . . . , argN):-predicate2(arg1, arg2, . . . , argN),


predicate3(arg1, arg2, . . . , argN), . . . , predicateN(arg1, arg2, . . . , argN).

Symbol Read as
:- If or implies that
, And
; Or
 Q
uestions
After writing facts and rules we will ask some questions. Those questions will be evaluated from
specified facts and rules. For example:

?- father(“shahid”, “saima”). Is Shahid father of Saima?


?- play(“ali”, “cricket”). Does Ali play cricket?
?- friend(“ali”, “farhan”). Is Ali friend of Farhan?
?- happy(“saima”). Is Saima happy?
Program Structure in Visual PROLOG

A Prolog program is composed of 7 different sections which are:

1) Compiler Directives (Optional): It is placed at the top of program. A number of compiler


features arecontrolled through compiler directives. These are instructions to the compiler to do
something beforeprogram execution.
2) Constants (Optional): In a Constants Section you can declare and use symbolic constants,
which you canthen use in your Visual Prolog programs. It’s just like #define directives in C or
final variables in Java.
3) Domains Section (Optional): The DOMAINS section is used to declare any domains that are
not VisualProlog standard domains (data types). You don't need to declare standard domains.
Used to declareuser defined data types.
Built-in Domains in Prolog:
char:A character, implemented as an unsigned byte. Syntactically, it is written as a character
surroundedby single quotation marks: 'a'.
integer: A signed quantity, having the natural size for the machine/platform architecture in
question.(Just as C)
long:A large signed quantity (32 bits).
real:A floating-point number, implemented as 8 bytes.
String: A sequence of characters, implemented as a pointer to a zero-terminated byte array, as
in C. Twoformats are permitted for strings:
A sequence of letters, numbers and underscores, provided the first character is lower-case.
A character sequence surrounded by a pair of double quotation marks.
symbol: A sequence of characters, implemented as a pointer to an entry in a hashed symbol-
table,containing strings. The syntax is the same as for strings.
4) Database Section (Optional): A Visual Prolog program is a collection of facts and rules.
Sometimes,while the program is running, you might want to update (change, remove, or add)
some of the facts theprogram operates on. In such a case, the facts constitute a dynamic or
internal database, which canchange while the program is running. Visual Prolog includes a
special section for declaring the facts thatare to be a part of the dynamic (or changing)
database; this is the facts or database section.
5) Predicates Section (Mandatory): The predicates you intend to use in your program must also
bedeclared in a predicates section; otherwise, Prolog won't know what you're talking about.
When youdeclare a predicate (function), you tell Visual Prolog which domains the arguments of
that predicate(function) belong to.
6) Clauses Section (Mandatory): The CLAUSES section contains the facts and rules that make up
yourprogram. Each CLAUSES section must begin with keyword CLAUSES as in the example
below:
CLAUSES
repeat().
repeat():-repeat().
A clause consists of either:Afact or a clause head followed by :- (a colon and hyphen) and then
by a listof predicate calls separated by commas or semicolons(rule)
Both facts and rules must be terminated by a period (.).

7) Goal Section (Mandatory): The GOAL section is where you put the built-in (internal) goal. A
VisualProlog program must always include exactly one GOAL section. Here we write questions.
Essentially, the GOAL section is the same as the body of a rule: it's simply a list of subgoals.
There aretwo differences between the GOAL section and a rule:
The GOAL keyword is not followed by ":-".
Prolog automatically executes the goal when the program runs.In a way, you can call Goal
section the main method of a prolog program.

 Case Study Family Tree

Salma Saeed Facts:


parent(“salma”,”saleem”).
parent(“salma”,”ali”).
parent(“saeed”,”saleem”).
parent(“saeed”,”ali”).
parent(“saleem”,”erum”).
Saleem Ali parent(“erum”,”kashif”).
parent(“erum”,”urooj”).
female(“salma”).
female(“erum”).
female(“urooj”).
Erum
male(“saeed”).
male(“saleem”).
male(“ali”).
Kashif Urooj male(“kashif”).

Figure 19: Case Study FamilyTree

 Questions

?- father(“saleem”,”ali”) Is saleem father of ali?


?- brother(“kashif”,”urooj”) Is kashifbrother of urooj?
?- father(X,”kashif”) Who is father of kashif?
?- mother(“erum”,”urooj”) Is erummother of urooj?
?- grandfather(X,”urooj”) Who is grandfather of urooj?
?- grandmother(“salma”,”erum”) Is salmagrandmother of erum?
?- father(“saeed”,X) Saeed is father of whom?
?- mother(“salma”,X) Salma is mother of whom?

 Example Code

PREDICATES
nondeterm parent(string,string)
nondeterm male(string)
nondeterm female(string)
nondeterm mother(string,string)
nondeterm father(string,string)
nondeterm brother(string,string)
nondeterm sister(string,string)
nondeterm grandmother(string,string)
nondeterm grandfather(string,string)

CLAUSES
parent("salma","saleem").
parent("salma","ali").
parent("saeed","saleem").
parent("saeed","ali").
parent("saleem","erum").
parent("erum","kashif").
parent("erum","urooj").
female("salma").
female("erum").
female("urooj").
male("saeed").
male("saleem").
male("ali").
male("kashif").
mother(Person1,Person2):- parent(Person1,Person2),female(Person1).
father(Person1,Person2):- parent(Person1,Person2),male(Person1).
brother(Person1,Person2):- parent(Person3,Person1),parent(Person3,Person2) ,male(Person1).
sister(Person1,Person2):- parent(Person3,Person1),parent(Person3,Person2),female(Person1).
grandmother(Person1,Person2):-
parent(Person1,Person3),parent(Person3,Person2),female(Person1).
grandfather(Person1,Person2):-
parent(Person1,Person3),parent(Person3,Person2),male(Person1).

GOAl
father(Who,"ali").

 Example Code
Note: Predicates declared nondeterm b/c program may have multiple solutions/

Lab Exercise

1. Covert following sentences into PROLOG FACTS and specify whether they represent
RELATIONSHIP or PROPERTY:

Declarative Sentence PROLOG FACT RELATIONSHIP orPROPERTY


MUET is university
Faheem likes icecream
Birds can fly
Switch is off
Sara is enemy of saima

2. Write down the PROLOG Rules for the following sentences:

Declarative Sentences PROLOG RULES


Person1 is sibling of Person2 if Person3 is
parent of
Person1 and Person3 is parent of Person2.
Person1 is child of Person2 if Person2 is parent
of
Person1.
It will rain today if clouds are heavy and air
pressure is low.
3. Run and display the results of the following goals in family tree case study program created
earlier.
a) Is saleem father of ali?
b) Is kashif brother of urooj?
c) Who is father of kashif?
d) Is erum mother of urooj?
e) Who is grandfather of urooj?
f) Is salma grandmother of erum?
g) Saeed is father of whom?
h) Salma is mother of whom?
i) who is grandfather of Kashif?

Conclusion:

Have you become familiar with visual PROLOG environment? What concepts did you gain
from this introductory practical on visual PROLOG? Comment
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____

References:
https://www.visual-prolog.com/vip/download/default.htm
https://www.visual-prolog.com/download/71/deBoer-BeginnersGuide.pdf
https://wiki.visual-prolog.com/index.php?title=Fundamental_Visual_Prolog
http://www.cse.unsw.edu.au/~billw/dictionaries/prolog/
http://www.aistudy.com/program/prolog/visual_prolog/Determinism%20Monitoring%20in
%20Visual%20Prolog.htm

The End
Lab#07 Tasks
CASE STUDY

EXAMPLE CODE
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence
Practical No. 8
Topic:Understanding variables and rules in visual PROLOG.
Student’s Roll no:_K18ES15 Points Scored: __________________________

Date of Conduct:_______________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand variables and rules in visual PROLOG.
 Create rules in visual PROLOG.

 EQUIPMENT & Tool:


 personal computer (PC)
 PROLOG

Variables in PROLOG
Like other programming languages the variables are used to temporarily store certain values.
They are used in place of unknown values. Consider the following example:
Ali is child of Saleem.
Sara is child of Salma.
Ahmed is child of Ali.
Kashif is child of Salma.
Muneer is child of Saleem.
Following is a program based on the predicates created from these sentences.

 Program

PREDICATES
child(string, string)
CLAUSES
child(“ali”, “saleem”).
child(“sara”, “salma”).
child(“ahmed”, “ali”).
child(“kashif”,”salma”).
child(“muneer”,”saleem”).
GOAL
child(“ali”,”saleem”).
 Program

The question that we are asking in the program is that


Is Ali child of Saleem?So answer is yes.
If we want to find that is Kashif child of Salma? Then we will write the goal as:
child(“kashif”,”salma”).
But if we want to find that who are the Childs of Salma? Then the first argument is unknown so in
the first argument we will place some variable say Child. Then our goal can be written as:
child(Child,”salma”).
Now it will return the following result:
Child=sara
Child=kashif
2 solutions
The variable starts with uppercase alphabets and they are not enclosed in double quotes as strings.
You can see that the arguments has first letter upper case, this indicates that argument is a variable
now which can be assigned any value or more in Logic programming terms can be bound to any
value. Thus the query that will be sent to Prolog can be read as “Does there exist a Child for salma”.
Here Prolog will go through its facts in order, trying to match each to the query. When it finds one
that matches in predicate name and 2nd argument, it will type "Child=" followed by the fact's first
argument, instead of typing yes. Or in technical jargon, it binds or matches Child to a value and
prints it.
Now let’s change the query or Goal to child(Child, “ali”), this time the result will be:
Child=ahmed
1 solution
In case there exists no predicate whose arguments can match the ones in query, for example, in this
case something like child(Child,”ahmed”) will have no solution possible so the result will be
No Solution

Rules in PROLOG
A rule is an expression that indicates that the truth of a particular fact depends upon one or more
otherfacts. The syntax can be
predicate1(arg1, arg2, ... argN):- predicate2(arg1, arg2, ... argN), predicate3(arg1, arg2, ...
argN),………,predicateN(arg1, arg2, ... argN).
This can be read as predicate1 is true only if predicate2 to predicateN are true.OrIt can be:
predicate1(arg1, arg2, ... argN):- predicate2(arg1, arg2, ... argN); predicate3(arg1, arg2, ...
argN);………;predicateN(arg1, arg2, ... argN).
This can be read as predicate1 is true if any one of predicate2 to predicateN is true (as ; represents
OR inProlog).The left hand side before :- of a rule is restricted to a single, positive, literal, which
means it mustconsist of a positive atomic expression. It cannot be negated and it cannot contain
logical connectives.Again taking the example of the program above, you can add a rule in the
Clauses likeparent(X,Y):- child(Y,X).This can be read as if Y is child of X then X is the parent of Y.
Similarly we can also haveGrandchild(X,Y):- child(Y,Z), child(Z,X).
This can be read as if Y is child of Z and Z is child of X then Y is Grandchild of X.It can also be
Grandchild(X,Y):-parent(Z,Y),parent(X,Z).

 Symbols used in PROLOG

Symbol Read as
:- If or implies that
, And
; Or
not Not

 Like- Hate Case Study

Declarative SentencesPROLOG facts


Kashif likes music.likes(“kashif”, “music”).
Kashif likes cricket. likes(“kashif”, “cricket”).
Sara likes chips. likes(“sara”, “chips”).
Sara likes mobile. likes(“sara”, “mobile”).
Kashif hates hockey. hates(“kashif”, “hockey”).
Kashif hates colddrinks. hates(“kashif”, “colddrinks”).
Sara hates driving. hates(“sara”, “driving”).
Sara hates parties. hates(“sara”, “parties”).

RulesPROLOG Rules
Sara hates everything Kashiflikes.hates(“sara”,X):-likes(“kashif”,X).
Kashif likes everything saralikes.likes(“kashif”,X):-likes(“sara”,X).

 Program

Questions (GOALS):
Does Kashif hate cricket? ?- hates(“kashif”,”cricket”).
Answer: No
Does Kashif like music? ?- likes(“kashif”,”music”).
Answer: Yes
What Sara likes? ?- likes(“sara”,X).
Answer:
X=chips
X=mobile
2 Solutions
Who likes music? ?-likes(X,”music”).
Answer:
X=kashif
1 Solution

Lab Exercise

 Cricket Case Study

There is a cricket team of 5 players; capabilities (properties) of each of the player are given
infollowing table.
Player Name Batsman Bowler Fielder
Sarfaraz ✓ ✓
Afridi ✓ ✓ ✓
Malik ✓ ✓ ✓
Hafiz ✓ ✓ ✓
Amir ✓ ✓

Write the facts from the above table create the rule for all-rounder and run following goals in
PROLOG.
1. Is Afridi all-rounder?
2. Is Malik all-rounder?
3. Who are all-rounders in the team?
4. Who is Batsman in the team?
5. Who is Bowler in the team?

CODE

1. Is Afridi all-rounder?

2. Is Malik all-rounder?

3. Who are all-rounders in the team?

4. Who is Bowler in the team?

5. Who is Batsman in the team?


Conclusion:

Have you become familiar with Variables and Rules in PROLOG? What concepts did you
gain from this practical? Comment
I have become familiar with visual prolog variables and on the basis of these variables
we designed different programs get output from these, its working it is quite easy to use.
From this lab I successfully understood the concept behind decision making on the basis
of knowledge we fed into any AI system.
References:
https://www.swi-prolog.org/pldoc/man?section=attvar
https://www.doc.gold.ac.uk/~mas02gw/prolog_tutorial/prologpages/vars.html
https://www.cpp.edu/~jrfisher/www/prolog_tutorial/4.html

The End
Lab#08 Tasks
PROGRAM

PREDICATES
child(string, string)
CLAUSES
child(“ali”, “saleem”).
child(“sara”, “salma”).
child(“ahmed”, “ali”).
child(“kashif”,”salma”).
child(“muneer”,”saleem”).

TASKS
FIND GOALS

 The question that we are asking in the program is that

 Is Ali child of Saleem? So answer is yes.

 If we want to find that is Kashif child of Salma? Then we will write the goal as:
 child(“kashif”,”salma”).

 But if we want to find that who are the Childs of Salma? Then the first argument is
unknown so in the first argument we will place some variable say Child. Then our goal
can be written as:child(Who,Whom).
Program

Questions (GOALS):
Does Kashif hate cricket? ?- hates(“kashif”,”cricket”).
Answer: No

Does Kashif like music? ?- likes(“kashif”,”music”).


Answer: Yes

What Sara likes? ?- likes(“sara”,X).

Who likes music? ?-likes(X,”music”).


Answer:
X=kashif
1 Solution
Lab Exercise

 Cricket Case Study

There is a cricket team of 5 players; capabilities (properties) of each of the player are given in
following table.
CODE
Player Batsman Bowle Fielder
Name r
Sarfaraz ✓ ✓

Afridi ✓ ✓ ✓

Malik ✓ ✓ ✓

Hafiz ✓ ✓ ✓

Amir ✓ ✓

Write the facts from the above table create the rule for all-rounder and run following goals
in PROLOG.
1. Is Afridi all-rounder?

2. Is Malik all-rounder?

3. Who are all-rounders in the team?


4. Who is Batsman in the team?

5. Who is Bowler in the team?

6. Who is fielder in the team?


MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 9
Topic:Exploring operators and built-in predicates of Visual PROLOG.
Student’s Roll no:K18ES15 Points Scored: __________________________

Date of Conduct:______________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand Operators in PROLOG.
 Understand Working of built-in predicates of PROLOG.
 Create simple programs using operators and built-in predicates of PROLOG.

 EQUIPMENT & Tool:


 personal computer (PC)
 visual PROLOG

Operators in visual PROLOG

 Arithmetic Operators
Prolog can perform all four basic arithmetic operations (addition, subtraction, multiplication, and
division) between integral and real values; the type of the result is determined according to the
following table.
Operand 1 Operator Operand 2 Result
Integral +, -, * Integral integral
Real +, -, * Integral real
In case
of Integral +, -, * Real real
Real +, -, * Real real
integral or real / integral or real real

Integral mod Integral integral


mixed integral arithmetic, involving both signed and unsigned quantities, the result is signed. The
size of the result will be that of the larger of the two operands.
The = operator (predicate) serves two purposes in Prolog. If the left hand side variable of the
expression is bound, it performs comparison else it assigns the value at right hand side to left hand
side variable.

 Relational Operators
Following is the list of relational operators used in PROLOG:

Relational Operator Meaning


> Greater Than
< Less Than
>= Greater Than or Equals To
<= Less Than or Equals To
= Equals To
<> or >< Not Equals To

Note that Prolog's "=" relation is equality (not assignment); it is the same as the "==" relation in C.

 Comparing Characteristics
Prolog converts the 'a' < 'b' to the equivalent arithmetic expression 97 < 98, using the
corresponding ASCII code value for each character.

 Comparing String
When two strings or symbols are compared, the outcome depends on a character-by-character
comparison of the corresponding positions.The comparison "antony" > "antonia" evaluates to true,
since the two symbols first differ at the position where one contains the letter y (ASCII value 79)
and the other the letter i (ASCII value 69).

Built-in Predicates
In many programming languages there are some built-in functions available. For example in JAVA
there Math.sin(), Math.cos(), Math.abs(), System.out.println() etc. are built-in functions. Similarly, in
PROLOG predicates are like functions and there are some built-in predicates available in PROLOG
some of them are explained below.

 write(value, value1,…..)
It prints the values concatenated with each other at output screen. E.g. write (“Hello World”,
1, A,B,b) will result in: Hello World1abb (assuming A and B are bound to a and b
respectively).
 nl:-It generates a line feed (new line). The same can be achieved by using \n in write.

 readint(X),readreal(Y),readchar(Z):- These are used to read integer, real, and character


valuesrespectively.

 readln(X):- Used to read Strings.

 fail:- If this predicate is encountered in any rule, that rule automatically fails.

 Example

PREDICATES
add3(integer, integer, integer, integer)
sub3(integer, integer, integer, integer)

CLAUSES
add3(A,B,C,Res):-Res=A+B+C.
sub3(A,B,C,Res):-Res=A-B-C.

GOAL
write("Enter 3 numbers, finishing each number with Enter key\n"),
readint(A),
readint(B),
readint(C),
add3(A,B,C,R1),
sub3(A,B,C,R2),
write("Result of A+B+C =",R1),
nl,
write("Result of A-B-C=",R2),
nl,
fail
Lab Exercise

1. Create a basic calculator prolog program for making basic calculations (add, subtract,
multiply,divide, average). Use separate goal statements for making each calculation (with
constant numeric values).

2. Continue calculator program with addition of using write() and read() predicates, for taking
numericinput from user and displaying text after program execution. Decorate your answer by
using morebuilt-in predicates.

Conclusion:

Have you become familiar with operators and built-in predicates in PROLOG? What
concepts did you gain from this practical? Comment
I have become familiar with visual prolog operators especially arithmetic operators it’s
working it is quite easy to use. We designed a simple arithmetic calculator that takes
input from user and performs different operations. From this lab I successfully
understood the concept behind decision making on the basis of knowledge we fed into
any AI system.
References:
http://www.aistudy.co.kr/program/prolog/visual_prolog/Comparisons.htm
http://www.aistudy.co.kr/program/prolog/visual_prolog/Arithmetic%20Expressions.htm
https://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms

The End

Lab#09 Tasks
EXAMPLE
LAB EXERCISE

1. Create a basic calculator prolog program for making basic calculations (add, subtract,
multiply, divide, average). Use separate goal statements for making each calculation (with
constant numeric values).
3. Continue calculator program with addition of using write() and read() predicates, for taking
numeric input from user and displaying text after program execution. Decorate your answer
by using more built-in predicates.
MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 10
Topic: Graph problem (A Path & Distance finding programin PROLOG).
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: _____________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand graph theory.
 Create simple programs to find path in an un-weighted graph using PROLOG.
 Create simple programs to find distance in a weighted graph using PROLOG.
 EQUIPMENT & TOOL:
 personal computer (PC)
 visual PROLOG

Graph Theory

 Graph
A graph is an abstract representation of a set of objects where some pairs of the objects are
connectedby links. The interconnected objects are the links that connect some pairs of vertices are
called edges. Typically, a graph is depicted in diagrammatic form as a set of dots for the vertices,
joined by lines or curves for the edges. Graphs are one of the objects of study in discrete
mathematics.The edges may be directed (asymmetric) or undirected (symmetric) .points and edges
are also called lines. In the most common sense of the term a graph is an ordered pair G = (V, E)
comparing a set V of vertices or nodes together with a set E of edges or lines, which are 2-element
subsets of V (i.e., an edge is related with two vertices, and the relation is represented as unordered
pair of the vertices with respect to the particular edge). To avoid ambiguity, this type of graph may
be described precisely as undirected and simple.
Figure 20 Graph

 A graph is simply the collection of nodes and vertices (edges or links).


 Graph G = (V, E) by defining a pair of sets:
V = a set of vertices
E = a set of edges

 Edges:
Each edge is defined by a pair of vertices
An edge connects the vertices that define it
In some cases, the vertices can be the same

 Vertices:
Vertices also called nodes
Denote vertices with labels

 Representation:
Represent vertices with circles, perhaps containing a label
Represent edges with lines between circles

 Example:
V = {A,B,C,D}
E = {(A,B),(A,C),(A,D),(B,D),(C,D)}

 Undirected graph
An undirected graph is one in which edges have no orientation. The edge (a, b) is identical to the
edge (b, a), i.e., they are not ordered pairs.

Figure 21 Undirected Graphs

 Directed graph
A directed graph or digraph is an ordered pair D = (V, A). Here V is a set whose elements are called
vertices or nodes and A is a set of ordered pairs of vertices, called arcs, directed edges, or arrows.
Figure 22 Directed Graphs

 Un-weighted graph and Weighted graph

In Weighted graphs cost value, weight or numerical value is associated with a given edge and in un-
weighted graph there is no cost value, weight or numerical value is associated for given edges.
*Note: Weighted graph can be directed or undirected.

Figure 23 Weighted Graph Un-weighted Graph

Un-weighted Graph
An un-weighted graph is one in which an edge does not have any cost or weight associated with it.
Figure below shows an un-weighted graph with 7 nodes (A, B. C. D. E. F& G).
 Links between nodes

The nodes which are connected together are said

Connected Nodes PROLOG facts


From A to B link(‘a’,’b’).
From A to C link(‘a’,’c’).
From B to D link(‘b’,’d’).
From C to D link(‘c’,’d’).
From D to B link(‘d’,’b’).
From D to E link(‘d’,’e’).
From D to F link(‘d’,’f’).
From E to F link(‘e’,’f’).
From F to G link(‘f’,’g’).

 Path between nodes

Sequence of edges connecting the nodes in between source and destination nodes is the path
between
source and destination nodes. For example from source node A to destination G there are four
paths:
Path 1 (A to G): A – B – D – F – G
Path 2 (A to G): A – B – D – E – F – G
Path 3 (A to G): A – C – D – E – F – G
Path 4 (A to G): A – C – D – F – G

 Rule to determine path exists between two nodes

The length of the path may vary. Minimum length of path is 1 and maximum can be any value
greater than one. Consider the path between the nodes A and B. Here the length of path is 1.

A B

In this case, if we want to determine whether path exists between A and B is simply to determine
whether link exists between A and B or not. If the link exists the path also exists, if link does not
exist the path does not exist.
So the prolog rule can be created as: path(N1,N2):-link(N1,N2).

Now consider another case in which we have to determine whether path exists between A and G or
not. Here the length of the path is 4.
There exists a path between nodes N1 and N2 if there is a path between N1 and N3; and N3 is
linked with N2.
This can be written in PROLOG as: path(N1,N2):-path(N1,N3),link(N3,N2).

Actually it is recursion in which the predicate “path” is calling itself. The recursive predicate is
executedin the manner shown below:

1stiteration: path(‘a’,’g’):-path(‘a’,’f’),link(‘f’,’g’).
2nditeration: path(‘a’,’f’):-path(‘a’,’d’),link(‘d’,’f’).
3rd iteration: path(‘a’,’d’):-path(‘a’,’c’),link(‘c’,’d’).
4thiteration: path(‘a’,’c’):-link(‘a’,’c’).

 Problem : Implement following graph and run different goals


 Program:

*Note: Declare predicate with keyword “nondeterm”.

 Goal Test Questions


Is there a link between nodes A and C? ?-link(‘a’,’c’).
Answer: Yes

Is there any path between nodes B and C? ?-path(‘b’,’c’).


Answer: No

B is linked with which points? ?-link(‘b’,X).


Answer:
X=d
1 Solution
D is linked with which points? ?-link(‘d’,X).
Answer:
X=b
X=e
X=f
3 Solutions

Which points are linked with D? ?-link(X,‘d’).


Answer:
X=b
X=c
2 Solutions

Which nodes are connected with node B and C? ?-link(X,'b'),link(X,'c').


Answer:
X=a
1 Solution

Which are the nodes to whom nodes B and C are connected? ?-link('b',X),link('c',X).
Answer:
X=d

Weighted Graph

 Weighted Graph

A weighted graph is one in which each of the edge is associated with a number known as weight.
Figure below shows a weighted graph where each of the edge is bounded with certain weight.
4
A B

2 3
8

D C

6 5
E
In the above figure there are 5 nodes (A, B, C, D& E). The arrows show the link between the nodes,
whereas the number associated with each of the arrow is the weight or distance of respective edge.
It is obvious from the above figure that:
Distance between nodes A & B is 4.
Distance between nodes A & C is 8.
Distance between nodes A & D is 2.
Distance between nodes B & C is 3.
Distance between nodes C & E is 5.
Distance between nodes D & E is 6.
Similarly the distance between nodes B and E is the sum of weighted edges included in the path
between B and E.

 Path between nodes

Path between B & E: B – C – E


Distance between nodes B & E is 3 + 5 = 8

There are 3 paths between nodes A & E:

Path 1 between nodes A & E: A – B – C – E


Distance between nodes A & E is 4 + 3 + 5 = 12
Path 2 between nodes A & E: A – C – E
Distance between nodes A & E is 8 + 5 = 13
Path 3 between nodes A & E: A – D – E
Distance between nodes A & E is 2 + 6 = 8

 Links and distances between nodes

The nodes which are connected together are said to have links between them.

Connected Nodes Distance PROLOG facts

From A to B 4 link(‘a’,’b’,4).
From A to C 8 link(‘a’,’c’,8).
From A to D 2 link(‘a’,’d’,2).
From B to C 3 link(‘b’,’c’,3).
From C to E 5 link(‘c’,’e’,5).
From D to E 6 link(‘d’,’e’,6).

 Rule to determine path exists between two nodes and distance between the nodes

Consider the path between the nodes A and B. Here the length of path is 1 and weight/distance of
the path is 4.
A 4 B

In this case, if we want to determine whether path exists between A and B is simply to determine
whether link exists between A and B or not. If the link exists the path also exists, if link does not
exist the path does not exist. The distance between the paths is simply the distance of the link.

So the prolog rule can be created as:path(N1,N2, Distance):-link(N1,N2, Distance).Where N1 is


source node, N2 is destination node and Distance is the weight of the link between N1 and N2.
Above rule can be read as path from N1 to N2 exists if N1 is linked to N2 and distance of the path is
Distance.

Now consider another case in which we have to determine whether path exists between A and E or
not. Here the length of the path is 3.
4
A B

5
E

There exists a path between nodes N1 and N2 if there is a path between N1 and N3; and N3 is
linked with N2 and the distance of the path is the sum of all the edges included in the path between
N1 and N2. This can be written in PROLOG as:

path(N1,N2,Distance):-path(N1,N3,Distance1),link(N3,N2,Distance2),Distance=Distance1+Distance2 .

4
A B Distance1

Distance = Distance1 + Distance2


3
C Distance = 4 + 3 + 5

Distance = 12

5 Distance2
E

 Problem: Implement following graph and run different goals


4
A B

2 8 3

D C

6 5
 Program

 Goal Test Questions

What is the distance of path between nodes A & B? ?-path(‘a’,’b’,Distance).


Answer:
Distance=4
1 solution

What is the distance of path between nodes A & C? ?- path(‘a’,’c’,Distance).


Answer:
Distance=8
Distance=7
2 solutions

What is the distance of path between nodes A & E? ?- path(‘a’,’e’,Distance).


Answer:
Distance=13
Distance=8
Distance=12
3 solutions

What is the distance of path between nodes B & E? ?- path(‘b’,’e’,Distance).


Answer:
Distance=8
1 solution

Which are the nodes whose path distance is 8? ?- path(N1,N2,8).


Answer:
N1=a, N2=c
N1=a, N2=e
N1=b, N2=e
3 solutions

Which are the nodes whose path distance is 7? ?- path(N1,N2,7).


Answer:
N1=a, N2=c
1 solution
Display all paths and their distances? ?- path(N1,N2,Distance).
Answer:
N1=a, N2=b, Distance=4
N1=a, N2=c, Distance=8
N1=a, N2=d, Distance=2
N1=b, N2=c, Distance=3
N1=c, N2=e, Distance=5
N1=d, N2=e, Distance=6
N1=a, N2=c, Distance=7
N1=a, N2=e, Distance=13
N1=a, N2=e, Distance=8
N1=b, N2=e, Distance=8
N1=a, N2=e, Distance=12
11 solutions

Distance of path between two nodes N1 and N2 is 8, the first node N1 is A find the second node N2.
?- path(‘a’,N2,8).
Answer:
N2=c
N2=e
2 solutions

Distance of path between two nodes N1 and N2 is 7, the first node N1 is A find the second node N2.
?- path(‘a’,N2,7).
Answer:
N2=c
1 solution

Distance of path between two nodes N1 and N2 is 12, the second node N2 is E find the first node N1.
?- path(N1,’e’,12).
Answer:
N1=a
1 solution

Lab Exercise

1. Implement the following un-weighted graph in PROLOG and run for following goals.

A B

C D

E F

 Is there a link between nodes A and F?

 Which points are linked with D?

 Which are the nodes to whom nodes D and C are connected?

2. Implement the following weighted graphs in PROLOG and run some goals.

3
4
A B C
2

F 2
3
6
1

Showing all paths and distances: D 5 E

Conclusion:

Have you become familiar with graph theory, can u create program to find path and
distance for a graph in PROLOG? What concepts did you gain from this practical? Comment
I have become familiar with visual prolog weighted and unweighted feature, its working
how we can generate different graphs and links between them according to our
requirement. We can also use distance function to measure distance between different
points. From this lab I successfully understood the concept behind decision making on
the basis of knowledge we fed into any AI system.
References:
https://rlgomes.github.io/work/prolog/2012/05/22/19.00-prolog-and-graphs.html
http://kti.ms.mff.cuni.cz/~bartak/prolog/graphs.html
https://stackoverflow.com/questions/21161624/define-graph-in-prolog-edge-and-path-finding-if-there-is-
a-path-between-two-ve
https://cs.ccsu.edu/~markov/ccsu_courses/prolog.txt

The End

Lab#10 Tasks
GRAPH PROGRAM:

 Goal
Test Questions

Is there a link between nodes A and C? ?-link(‘a’,’c’).


Is there any path between nodes B and C? ?-path(‘b’,’c’).
GRAPH

4
A B

2 3
8

D C

6 5
E

 Program

 Goal Test Questions

What is the distance of path between nodes A & B? ?-path(‘a’,’b’,Distance).

What is the distance of path between nodes A & C? ?- path(‘a’,’c’,Distance).


What is the distance of path between nodes A & E? ?- path(‘a’,’e’,Distance).

What is the distance of path between nodes B & E? ?- path(‘b’,’e’,Distance).

Which are the nodes whose path distance is 8? ?- path(N1,N2,8).

Which are the nodes whose path distance is 7? ?- path(N1,N2,7).

Display all paths and their distances? ?- path(N1,N2,Distance).


Distance of path between two nodes N1 and N2 is 8, the first node N1 is A find the second node N2.
?- path(‘a’,N2,8).

Distance of path between two nodes N1 and N2 is 7, the first node N1 is A find the second node N2.
?- path(‘a’,N2,7).

Distance of path between two nodes N1 and N2 is 12, the second node N2 is E find the first node N1.
?- path(N1,’e’,12).
Lab Exercise

3. Implement the following un-weighted graph in PROLOG and run for following goals.

A B

C D

E F

 Is there a link between nodes A and F?

 Which points are linked with D?

 Which are the nodes to whom nodes D and C are connected?


4. Implement the following weighted graphs in PROLOG and run some goals.

5. What is the distance of path between nodes A & B?

6. What is the distance of path between nodes B&E?

7. Which are the nodes whose path distance is 9?

8. Display all paths and their distances?


MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronics Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 11
Topic: Simple Tic-Tac-Toe game in visual PROLOG.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: ________________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand tic-tac-toe game states.
 Create simple programs in PROLOG to find states and winners for tic-tac-toe game.

 EQUIPMENT & Tool:


 personal computer (PC)
 visual PROLOG

Tic-Tac-Toe Game

 Tic-Tac-Toe Game
Tic-tac-toe, also called noughts and rosses (in the British Commonwealth countries) and X's and O's
inthe Republic of Ireland, is a pencil-and paper game for two players, X and O, who take turns
marking the spaces in a 3×3 grid. The X player usually goes first. The player who succeeds in
placing three marks in a horizontal, vertical, or diagonal row wins the game.

The following example game is won by the first player, X:

Players soon discover that best play from both parties leads to a draw (often referred to as cat or
cat'sgame). Hence, tic-tac-toe is most often played by young children.

Players in Tic-Tac-Toe Game


There are only two players in the game. One will choose the crosses and other will choose noughts
called circles. In PROLOG this could be represented as fact.
player(string,string)

Here the predicate player contains two string arguments, first tells the name of the player and the
second tell whether the player chooses crosses or circles. For example if Ali chooses crosses and
Kashif chooses circles then the facts can be written as:

player(“ali”,”crosses”).

player(“kashif”,”circles”).

States of tic-tac-toe boxes


The tic-tac-toe contains 9 square boxes numbered as shown in below figure. Each of the boxes will
either contain circle (O), cross (X) or can be empty. We will maintain the state of tic-tac-toe by
creating two predicates:

circle(integer)

cross(integer)

Both predicates contain one argument that is the box number in which cross or circle is placed. For
the state of tic-tac-toe shown in second figure the facts can be written as:

1 2 3 O X X

4 5 6 X O
circle(1).
circle(6).
circle(7).
circle(9).
cross(2).
cross(3).
cross(5).
cross(8).

 Condition for crosses to win

The crosses will win if any one of the crosses positions is present in the current state of the game:

X X X X

X X X X

X X X X

X X X X

X X X X

X X X X

So we can write a rule crossesWin() as follows:

crossesWin():-cross(1), cross(2), cross(3); cross(4), cross(5), cross(6);

cross(7), cross(8), cross(9);cross(1), cross(4), cross(7);

cross(2), cross(5), cross(8);cross(3), cross(6), cross(9);

cross(1), cross(5), cross(9);cross(3), cross(5), cross(7).

 Condition for circles to win


The circles will win if any one of the circles positions is present in the current state of the game:

O O O O

O O O O

O O O O

O O O O

O O O O

O O O O

So we can write a rule circlesWin() as follows:

circlesWin():-circle(1), circle(2), circle(3); circle(4), circle(5), circle(6);

circle(7), circle(8), circle(9);circle(1), circle(4), circle(7);

circle(2), circle(5), circle(8);circle(3), circle(6), circle(9);

circle(1), circle(5), circle(9);circle(3), circle(5), circle(7).

 Condition for player to win

In order to determine which player wins we must know two things: First, whether player has
chosen crosses or circles. Second, whether cross wins or circle wins.

If circles win then the player who has chosen circles will win.

If crosses win then the player who has chosen crosses will win.

This rule can be written in prolog as:

wins(Player):-crossesWin(),player(Player,”crosses”).

wins(Player):-circlesWin(),player(Player,”circles”).

 Tic-Tac-Toe Example 1

Suppose there are two players: Player 1= Ali, he chooses circles and Player 2= Kashif, he chooses
crosses. The current state of the game is shown below. Write a PROLOG program to find who wins?
X O X

X O O

X O

 PROLOG Program:

PREDICATES
player(string,string)
circle(integer)
cross(integer)
circlesWin()
crossesWin()
wins(string)

CLAUSES
player(“ali”,”circles”).
player(“kashif”,”crosses”).

cross(1).
cross(3).
cross(4).
cross(7).
circle(2).
circle(5).
circle(6).
circle(9).

crossesWin():-cross(1), cross(2), cross(3);


cross(4), cross(5), cross(6);
cross(7), cross(8), cross(9);
cross(1), cross(4), cross(7);
cross(2), cross(5), cross(8);
cross(3), cross(6), cross(9);
cross(1), cross(5), cross(9);
cross(3), cross(5), cross(7).

circlesWin():-circle(1), circle(2), circle(3);


circle(4), circle(5), circle(6);
circle(7), circle(8), circle(9);
circle(1), circle(4), circle(7);
circle(2), circle(5), circle(8);
circle(3), circle(6), circle(9);
circle(1), circle(5), circle(9);
circle(3), circle(5), circle(7).

wins(Player):-crossesWin(),player(Player,”crosses”).
wins(Player):-circlesWin(),player(Player,”circles”).

GOAL
wins(Who).
 Tic-Tac-Toe Example 2

Suppose there are two players: Player 1= Saima, she chooses circles and Player 2= Salma, she chooses
crosses. The current state of the game is shown below. Write a PROLOG program to find who wins?
O O X

O X

X X O

 PROLOG Program:

PREDICATES
player(string,string)
circle(integer)
cross(integer)
circlesWin()
crossesWin()
wins(string)

CLAUSES
player(“saima”,”circles”).
player(“salma”,”crosses”).

cross(3).
cross(6).
cross(7).
cross(8).
circle(1).
circle(2).
circle(5).
circle(9).

crossesWin():-cross(1), cross(2), cross(3);


cross(4), cross(5), cross(6);
cross(7), cross(8), cross(9);
cross(1), cross(4), cross(7);
cross(2), cross(5), cross(8);
cross(3), cross(6), cross(9);
cross(1), cross(5), cross(9);
cross(3), cross(5), cross(7).

circlesWin():-circle(1), circle(2), circle(3);


circle(4), circle(5), circle(6);
circle(7), circle(8), circle(9);
circle(1), circle(4), circle(7);
circle(2), circle(5), circle(8);
circle(3), circle(6), circle(9);
circle(1), circle(5), circle(9);
circle(3), circle(5), circle(7).

wins(Player):-crossesWin(),player(Player,”crosses”).
wins(Player):-circlesWin(),player(Player,”circles”).

GOAL
wins(Who).
 Goal Test Questions
Does Salma win? ?-wins(“salma”).
Answer: No

Does Saima win? ?-wins(“saima”).


Answer: Yes

What saima has chosen? ?-player(“saima”,X).


Answer:
X=circles
1 Solution

Where are crosses placed? ?-cross(X).


Answer:
X=3
X=6
X=7
X=8
4 Solutions

Where are circles placed? ?-circle(X).


Answer:
X=1
X=2
X=5
X=9
4 Solutions

Who wins? ?-wins(X).


Answer:
X=saima
1 Solution

Lab Exercise

1. Suppose there are two players: Player 1= Akhter, he chooses circles and Player 2= Shahid,
he
chooses crosses. The current state of the game is shown below.Write a PROLOG program
to findwho wins?
2. Suppose there are two players: Player 1= Ali, he chooses circles and Player 2= Kashif, he
choosescrosses. Now we extend our game to 4 X 4 square boxes. The current state of the
game is shownbelow.Write a PROLOG program to find who wins?

Conclusion:

Have you become familiar with states of Tic-Tac-Toe game? , can u create program to find
which player wins Tic-Tac-Toe game?
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____

References:
https://mezohelp.blogspot.com/2014/05/tictactoe-game-using-swi-prolog.html
https://github.com/GoodDeeds/Tic-Tac-Toe-Prolog
https://courses.cs.washington.edu/courses/cse341/03sp/slides/PrologEx/tictactoe.pl.txt
https://swish.swi-prolog.org/p/Tic-Tac-Toe.swinb

The End
MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 12
Topic: Medical Expert System Case Study using PROLOG.
Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: ________________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
 Understand expert system.
 Create simple programsin SWI-PROLOG as a practical implementation of medical expert system
Case study.

 EQUIPMENT & Tool:


 personal computer (PC)
 SWI PROLOG

Expert System
In artificial intelligence, an expert system is a computer system that emulates the decision-making
ability of a human expert. Expert systems are designed to solve complex problems by reasoning
through bodies of knowledge, represented mainly as if–then rules.
Figure 24 Expert system components

Medical Expert System Case Study


For medical expert systemthe knowledge base contain medical information, the symptoms of
patient would be used as a query, and the advice would be a diagnosis of patient’s illness.
Medical expert systems are very helpful. In Medical expert system we have a list of diseases and
their symptoms. Questions reveal symptoms. Medical expert system finds a disease to match
symptoms. In market some of the well-known expert systems in the field of medical are listed
below:

 MYCIN
 BLUE BOX
 VM
 ANNA

Here is diagram of a typical medical expert system.


Figure 25 Hierarchy Diagram

Steps to implement Medical Expert System Case Study

 Download Tool SWI-PROLOG. As SWI-PROLOG provides us free prolog environment with many
advanced libraries and also provide us online environment to write and run code online.

 Download from link given blow.

https://swish.swi-prolog.org/download/stable

 To use online version of SWI-PROLOG go to the link given below.

https://swish.swi-prolog.org/
 To implement medical expert system in SWI-PROLOG.

 Write hypothesis about diseases.

 Make rule so that questions can be asked from user and based on hypothesis disease will be
diagnosed and suggestions will be given to the patient.

 Sample Code for MES

/*Source code of expert system*/

go:-

hypothesis(Disease),

write('I believe that the patient have'),

write(Disease),

nl,

write('TAKE CARE '),

undo.

/*Hypothesis that should be tested*/

hypothesis(cold) :- cold, !.

hypothesis(flu) :- flu, !.

hypothesis(typhoid) :- typhoid, !.

hypothesis(measles) :- measles, !.

hypothesis(malaria) :- malaria, !.

hypothesis(unknown). /* no diagnosis*/

/*Hypothesis Identification Rules*/

cold :-
verify(headache),

verify(runny_nose),

verify(sneezing),

verify(sore_throat),

write('Advices and Sugestions:'),

nl,

write('1: Tylenol/tab'),

nl,

write('2: panadol/tab'),

nl,

write('3: Nasal spray'),

nl,

write('Please weare warm cloths Because'),

nl.

flu :-

verify(fever),

verify(headache),

verify(chills),

verify(body_ache),

write('Advices and Sugestions:'),

nl,
write('1: Tamiflu/tab'),

nl,

write('2: panadol/tab'),

nl,

write('3: Zanamivir/tab'),

nl,
write('Please take a warm bath and do salt gargling Because'),

nl.

typhoid :-

verify(headache),

verify(abdominal_pain),

verify(poor_appetite),

verify(fever),

write('Advices and Sugestions:'),

nl,

write('1: Chloramphenicol/tab'),

nl,

write('2: Amoxicillin/tab'),

nl,

write('3: Ciprofloxacin/tab'),

nl,

write('4: Azithromycin/tab'),

nl,

write('Please do complete bed rest and take soft Diet Because'),

nl.

measles :-

verify(fever),

verify(runny_nose),

verify(rash),

verify(conjunctivitis),

write('Advices and Sugestions:'),

nl,
write('1: Tylenol/tab'),

nl,

write('2: Aleve/tab'),

nl,

write('3: Advil/tab'),

nl,

write('4: Vitamin A'),

nl,

write('Please Get rest and use more liquid Because'),

nl.

malaria :-

verify(fever),

verify(sweating),

verify(headache),

verify(nausea),

verify(vomiting),

verify(diarrhea),

write('Advices and Sugestions:'),

nl,

write('1: Aralen/tab'),

nl,

write('2: Qualaquin/tab'),

nl,

write('3: Plaquenil/tab'),

nl,

write('4: Mefloquine'),
nl,

write('Please do not sleep in open air and cover your full skin Because'),

nl.

/* how to ask questions */

ask(Question) :-

write('Does the patient have following symptom:'),

write(Question),

write('? '),

read(Response),

nl,

( (Response == yes ; Response == y)

->

assert(yes(Question)) ;

assert(no(Question)), fail).

:- dynamic yes/1,no/1.

/*How to verify something */

verify(S) :-

(yes(S)

->

true ;

(no(S)

->

fail ;

ask(S))).

/* undo all yes/no assertions*/

undo :- retract(yes(_)),fail.
undo :- retract(no(_)),fail.

undo.

 Save file as with .pl and run with SWI-PROLOG.

 Or Run online.

Lab Exercise
3. Modify this medical expert system case study by adding some diseases and their
symptoms.Run the code , and test for different diseases.

Conclusion:

Have you become familiar with expert system? can you create programs using SWI-PROLOG to
practically implement expert systems?
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________

References:
https://swish.swi-prolog.org/
https://swish.swi-prolog.org/
https://en.wikipedia.org/wiki/Comparison_of_Prolog_implementations
http://www.david-reitter.com/compling/prolog/compare.html
https://www.youtube.com/watch?v=pFdagVD2a-Y
https://www.amzi.com/ExpertSystemsInProlog/02usingprolog.php
https://github.com/topics/expert-system?l=prolog
https://www.metalevel.at/prolog/expertsystems

The End

Lab tasks
4. Modify this medical expert system case study by adding some diseases and their
symptoms.Run the code , and test for different diseases.

CODE

/*Source code of expert system*/

go:-

hypothesis(Disease),

write('I believe that the patient have '),


write(Disease),

nl,

write('TAKE CARE '),

undo.

/*Hypothesis that should be tested*/

hypothesis(covid) :- covid, !.

hypothesis(kidneystone) :- kidneystone, !.

hypothesis(diabetes) :- diabetes, !.

hypothesis(asthma) :- asthma, !.

hypothesis(cold) :- cold, !.

hypothesis(flu) :- flu, !.

hypothesis(typhoid) :- typhoid, !.

hypothesis(measles) :- measles, !.

hypothesis(malaria) :- malaria, !.
hypothesis(unknown). /* no diagnosis*/

/*Hypothesis Identification Rules*/

covid :-

verify(difficulty_breathing),

verify(chest_pain),

verify(movement),

verify(diarrhoea),

write('Advices and Sugestions:'),

nl,

write('1: oxygen '),

nl,

write('2: mask'),

nl,

write('3: hand_wash'),
nl,

write('Please isolate'),

nl.

kidneystone :-

verify(pain_in_back ),

verify(vomiting),

verify(seeing_blood_in_urine),

verify(Fever),

write('Advices and Sugestions:'),

nl,

write('1: water '),

nl,

write('2: ibuprofen'),

nl,
write('3: naproxen'),

nl,

write('Please avoid high protiens food'),

nl.

diabetes :-

verify(urinate ),

verify(thirsty),

verify(hungry),

verify(tired),

write('Advices and Sugestions:'),

nl,

write('1: dapagliflozin '),

nl,

write('2: glyburide'),
nl,

write('3: linagliptin'),

nl,

write('Please avoid sweet'),

nl.

asthma :-

verify(Shortness_of_breath),

verify(chest_tightness),

verify(wheezing),

verify(flu),

write('Advices and Sugestions:'),

nl,

write('1: albuterol'),

nl,
write('2: Xopenex'),

nl,

write('3: ProAir_HFA'),

nl,

write('Please avoid dusty environment'),

nl.

covid :-

verify(difficulty_breathing),

verify(chest_pain),

verify(movement),

verify(diarrhoea),

write('Advices and Sugestions:'),

nl,

write('1: oxygen '),


nl,

write('2: mask'),

nl,

write('3: hand_wash'),

nl,

write('Please isolate'),

nl.

cold :-

verify(headache),

verify(runny_nose),

verify(sneezing),

verify(sore_throat),

write('Advices and Sugestions:'),

nl,
write('1: Tylenol/tab'),

nl,

write('2: panadol/tab'),

nl,

write('3: Nasal spray'),

nl,

write('Please weare warm cloths Because'),

nl.

cold :-

verify(headache),

verify(runny_nose),

verify(sneezing),

verify(sore_throat),

write('Advices and Sugestions:'),

nl,
write('1: Tylenol/tab'),

nl,

write('2: panadol/tab'),

nl,

write('3: Nasal spray'),

nl,

write('Please weare warm cloths Because'),

nl.

flu :-

verify(fever),

verify(headache),

verify(chills),

verify(body_ache),

write('Advices and Sugestions:'),


nl,

write('1: Tamiflu/tab'),

nl,

write('2: panadol/tab'),

nl,

write('3: Zanamivir/tab'),

nl,

write('Please take a warm bath and do salt gargling Because'),

nl.

typhoid :-

verify(headache),

verify(abdominal_pain),

verify(poor_appetite),

verify(fever),
write('Advices and Sugestions:'),

nl,

write('1: Chloramphenicol/tab'),

nl,

write('2: Amoxicillin/tab'),

nl,

write('3: Ciprofloxacin/tab'),

nl,

write('4: Azithromycin/tab'),

nl,

write('Please do complete bed rest and take soft Diet Because'),

nl.

measles :-

verify(fever),
verify(runny_nose),

verify(rash),

verify(conjunctivitis),

write('Advices and Sugestions:'),

nl,

write('1: Tylenol/tab'),

nl,

write('2: Aleve/tab'),

nl,

write('3: Advil/tab'),

nl,

write('4: Vitamin A'),

nl,

write('Please Get rest and use more liquid Because'),


nl.

malaria :-

verify(fever),

verify(sweating),

verify(headache),

verify(nausea),

verify(vomiting),

verify(diarrhea),

write('Advices and Sugestions:'),

nl,

write('1: Aralen/tab'),

nl,

write('2: Qualaquin/tab'),

nl,
write('3: Plaquenil/tab'),

nl,

write('4: Mefloquine'),

nl,

write('Please do not sleep in open air and cover your full skin Because'),

nl.

/* how to ask questions */

ask(Question) :-

write('Does the patient have following symptom:'),

write(Question),

write('? '),

read(Response),

nl,

( (Response == yes ; Response == y)


->

assert(yes(Question)) ;

assert(no(Question)), fail).

:- dynamic yes/1,no/1.

/*How to verify something */

verify(S) :-

(yes(S)

->

true ;

(no(S)

->

fail ;

ask(S))).

/* undo all yes/no assertions*/


undo :- retract(yes(_)),fail.

undo :- retract(no(_)),fail.

undo.

RESULT

TEST 01

TEST 02
TEST 03
MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear

Artificial Intelligence

Practical No. 15

Topic: Implementation of Single Layer Perceptron Learning Algorithm


Student’s Roll no: K18ES15 Points Scored: __________________________

Date of Conduct: ________________ Teacher’s Signature: ___________________

LAB DATA ANALYSIS ABILITY TO


SUBJECT CALCULATION OBSERVATION/
PERFORMANCE KNOWLEDGE
AND CONDUCT PRESENTATION
AND CODING RESULTS
SCORE
INDICATOR INTERPRETATION EXPERIMENT

 OBJECTIVES: Upon successful completion of this practical, the students will be able to:
To become familiar with neural networks learning algorithms from available examples.
 Provide knowledge of learning algorithm in neural networks.

 EQUIPMENT & Tool:


 personal computer (PC)
 MATLAB

Implementation of Single Layer Perceptron Learning Algorithm


Outcomes:
The student will be able to,

 Have an understanding of the concepts and techniques of neural networks through the study
of the most important neural network models.

 Discuss the main factors involved in achieving good learning and generalization performance
in neural network systems.
 Use the current techniques and tools required for computing practice.

Theory:
Neural networks are a branch of ―Artificial Intelligence". Artificial Neural Network is a system
loosely modelled based on the human brain. Neural networks are a powerful technique to solve
many real world problems. They have the ability to learn from experience in order to improve
their performance and to adapt themselves to changes in the environment. In addition to that
they are able to deal with incomplete information or noisy data and can be very effective
especially in situations where it is not possible to define the rules or steps that lead to the
solution of a problem. In a nutshell a Neural network can be considered as a black box that is
able to predict an output pattern when it recognizes a given input pattern. Once trained, the
neural network is able to recognize similarities when presented with a new input pattern,
resulting in a predicted output pattern. In late 1950s, Frank Rosenblatt introduced a network
enhanced version of McCulloch-Pitts Threshold Logic Unit (TLU) model. Rosenblatt's model of neuron, a
perceptron, was the result of merger between two concepts from the 1940s, McCulloch-Pitts model of
an artificial neuron and Hebbian learning rule of adjusting weights. In addition to the variable weight
values, the perceptron model added an extra input that represents bias.

Thus, the modified equation is now as follows:

where b represents the bias valuecomposed of the units that were

5. Algorithm:
Perceptron Learning Algorithm:
The perceptron learning rule was originally developed by Frank Rosenblatt in the late
1950s. Training patterns are presented to the network's inputs; the output is computed.
Then the connection weightswjare modified by an amount that is proportional to the
product of
 the difference between the actual output, y, and the desired output, d, and
 the input pattern, x.

The algorithm is as follows:


1. Initialize the weights and threshold to small random numbers.
2. Present a vector x to the neuron inputs and calculate the output. 3. Update the
weights
according to:
Where
 d is the desired output,
 t is the iteration number, and
 eta is the gain or step size, where 0.0 < n < 1.0
4. Repeat steps 2 and 3 until
1. the iteration error is less than a user-specified error threshold or
2. a predetermined number of iterations have been completed.
Learning only occurs when an error is made; otherwise the weights are left unchanged

Problem Statement:
Implement AND function using perceptron model
Truth table for AND function is:
6. Conclusion:

Single layer perceptron learning algorithm is implemented for AND function. It is used for
train the iterations of neural network. Neural network mimics the human brain and
perceptron learning algorithm trains the neural network according to the input given.

You might also like