You are on page 1of 46

Department of Information Systems ‫قسم نظم المعلومات‬

Lab Manual
ISM 383
Knowledge-Based
Systems
Department of Information systems
College of Computer Science
King Khalid University

Course Coordinator

Mohammad Ashiquee Rasool

IS Lab Manual - 2015 1


Department of Information Systems ‫قسم نظم المعلومات‬

ISM 383
Course Name Course Code
Knowledge-Based Systems - LAB ISM 383
Lab Syllabus with Work Plan
Lab No. Topics to be covered
LAB 1 Overview and Introduction of CLIPS Software
 How to define a variable?
 How to check list of variable?
 How to delete any specific variable?
 How to reset CLIPS memory?
LAB 2 Defining the Rules
• How to define a rule and assign value to it?
LAB 3 Defining the Rules
• Defining the rules for matching things
LAB 4 Use of NOT operator in CLIPS by defining single condition
Use of OR operator by defining multiple conditions
Use of AND operator by defining multiple conditions
LAB 5 Use of AND / OR together by defining at least 3 or more conditions
LAB 6 Use of test operation in CLIPS
• How to find Less from 2 given numbers
• How to find Less from more than 2 numbers
• How to find Greater from 2 given numbers
• How to find Greater from more than 2 numbers
LAB 7 Representation of Mathematical expressions in CLIPS
• Use of mathematical operations on simple string
• Use of mathematical operations on complex string
LAB 8 Working with strings
• Functions for operations on strings
LAB 9 Combination of mathematical and logical operations
LAB 10 Assigning multiple values through multi valued wildcard
Extracting the multiple values on different conditions
LAB 11 Forward chain algorithm, Backward chain algorithm
LAB 12 Defining a template in CLIPS in shape of a form
Assigning multiple value using single command
Retrieving the assigned data from template
LAB 13&14 Expert System Development
LAB 15 Final LAB Exam

Software(s)/Tools Used
 CLIPS SOFTWARE
References
 Lecture notes
 http://users.csc.calpoly.edu/~fkurfess/481/W02/Lab

Mr. Mohammad Ashiquee Rasool IS Department Approval

IS Lab Manual - 2015 2


Department of Information Systems ‫قسم نظم المعلومات‬

CLIPS is an expert system tool originally developed by the Software Technology Branch
(STB), NASA/Lyndon B. Johnson Space Center. Since its first release in 1986, CLIPS has
undergone continual refinement and improvement. It is now used by thousands of people
around the world. CLIPS is designed to facilitate the development of software to model
human knowledge or expertise. There are three ways to represent knowledge in CLIPS:
• Rules, which are primarily intended for heuristic knowledge based on experience.
• Deffunctions and generic functions, which are primarily intended for procedural
knowledge. vi —
• Object-oriented programming, also primarily intended for procedural knowledge. The
five generally accepted features of object-oriented programming are supported: classes,
message-handlers, abstraction, encapsulation, inheritance, polymorphism. Rules may
pattern match on objects and facts.

CLIPS is a type of computer language designed for writing applications called expert
systems. An expert system is a program which is specifically intended to model human
expertise or knowledge. In contrast, common programs such as payroll programs, word
processors, spreadsheets, computer games, and so forth, are not intended to embody
human expertise or knowledge. (One definition of an expert is someone more than 50 miles
from home and carrying a briefcase.) CLIPS is called an expert system tool because it is a
complete environment for developing expert systems which includes features such as an
integrated editor and a debugging tool. The word shell is reserved for that portion of CLIPS
which performs
inferences or reasoning. The CLIPS shell provides the basic elements of an expert system: 1.
fact-list, and instance-list: Global memory for data 2. knowledge-base: Contains all the
rules, the rule-base 3. inference engine: Controls overall execution of rules A program
written in CLIPS may consist of rules, facts, and objects. The inference engine decides
which rules should be executed and when. A rule-based expert system written in CLIPS is a
data-driven program where the facts, and objects if desired, are the data that stimulate
execution via the inference engine.

IS Lab Manual - 2015 3


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 1
Objective:
Understanding the CLIPS environment and learn to use basic commands and structure in
CLIPS

Activities:
Activity 1: Open CLIPS and run the basic commands
Activity 2: Insert a fact/variable in CLIPS
Activity 3:How to display variables in CLIPS?
Activity 4: How to delete a variable in CLIPS?

Learning outcome:
Get basic overview of CLIPS environment

Activity 1: Open CLIPS and run the following basic commands

 The Beginning and the End


 exit
 clear
 reset
 run
 assert

The Beginning and the End


To begin CLIPS, just enter the appropriate run command for your system. You should see
the CLIPS prompt appear as follows:

CLIPS>

(exit)

Shuts down CLIPS

(clear)

IS Lab Manual - 2015 4


Department of Information Systems ‫قسم نظم المعلومات‬

Removes all program and data from memory. Equivalent to shutting down and restarting
CLIPS.

(reset)

Removes dynamic information from memory and resets the agenda.

(run)

Starts executing a CLIPS program

Activity 2: How to insert a fact/variable in CLIPS?


(assert (color green))

This command will enter a variable name “color green”

(assert (animal cat))

This command will enter a variable name “animal cat”

Activity 3:How to display variables in CLIPS?


(facts)

This command will display the saved variable in clips with respective positions.

IS Lab Manual - 2015 5


Department of Information Systems ‫قسم نظم المعلومات‬

Activity 4: How to delete a variable in CLIPS?


(retract number of variable)

E.g: (retract 3)

This command will delete the variable at position number 3.

Exercise 1:
Enter at least 5 different names with the using the assert command. E.g: (assert
(name tariq))

Exercise2:
Retract the variable enter at position number 3 and 5, as entered in previous
exercise.

Note: CLIPS is case sensitive; so you should use the command in the same case as
explained.

IS Lab Manual - 2015 6


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 2
Objective:
Learn to define rules in CLIPS and get basic understanding of rule execution.
Understanding the role of antecedents and consequences in rule.

Activities:
Activity 1: Assert some facts. Define a rule in CLIPS. The rule should check the condition
and if the condition is true, it should assert a fact in the memory.

Learning outcome:
Understanding the role of CLIPS rules in knowledge-based system.

How to define rules in CLIPS?


First enter the required fact and facts in the Clips working memory which will be used
during the execution of rule.

(assert (animal duck))

You can check using (facts) command to make sure that variable entered correctly or not.
Now enter the following rule

(defrule duck
(animal duck)
=>
(assert (sound-is quack)))

Explanation:

Rule has 3 parts:

The first part, (defrule duck, simply gives the rule a unique name.

The second part, (animal duck), is the pattern (condition part) of the rule

Last part, (assert (sound-is quack)), is the action (the action part).

IS Lab Manual - 2015 7


Department of Information Systems ‫قسم نظم المعلومات‬

What this rule will do?

This rule will check that if a fact (animal duck) is defined then it will assign the sound
quack to the animal duck.

If no fact is defined then sound will not be allocated and you will not see any changes.

Complete Rule exercise: (Enter the following commands one by one)


CLIPS> (assert (animal duck))

CLIPS> (facts) // to make sure about variable

CLIPS> (defrule duck


(animal duck)
=>
(assert (sound-is quack)))

CLIPS> (run) // To execute the variable

CLIPS> (facts) // To Check the variable sound quack inserted or not

Screenshot:

IS Lab Manual - 2015 8


Department of Information Systems ‫قسم نظم المعلومات‬

Exercise 1:
Assert a Course 383 and Define a rule to assign teacher to the course 383. Assign the
teacher name Raja by executing the same rule

Exercise 2:
Assert some courses including "Course 383" and assign the following using a rule:

Theory teacher Ashique

Practical Teacher Raja

IS Lab Manual - 2015 9


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 3
Objective:
Understanding pattern matching in an expert system. pattern can be matched against a
pattern entity. A pattern entity is either a fact or an instance of a user-defined class.

Activities:
Activity 1: Assert some facts. Define a rule in CLIPS. The rule should mach the pattern of
existing fact and display <variable name> found like "animal found animal found animal
found".

Activity 2: Assert some facts. Define a rule in CLIPS. The rule should mach the pattern of
existing fact and display <value of variable> found like "dog found cat found camel found".

Learning outcome:
Learn pattern matching pattern matching in an expert system using CLIPS.

Activity:

Defining a rule for matching things:


Insert the following facts:

(animal dog)

(animal cat)

(animal camel)

(animal tiger)

(animal duck)

(animal turtle)

Now define the following rule:

IS Lab Manual - 2015 10


Department of Information Systems ‫قسم نظم المعلومات‬

(defrule name

(animal ?name)

=>

(printout t ?name " found " crlf))

Execute the rule by using (run) command

You will see that it will match the name of animal variable and display the result.

Output Screen Shot

Exercise 1:
Assert some student names and faculty names in the working memory. Write two different
rules; one to display the faculty names and one to display the students name and execute
them.

IS Lab Manual - 2015 11


Department of Information Systems ‫قسم نظم المعلومات‬

Lab 4

Objective:
To implement and use AND operator and OR operator in CLIPS.

Activities:
Activity 1: Assert some car name and then assert some cars which have four wheel drive.
Define a rule in CLIPS. The rule should mach the pattern of existing fact and display the cars
which do not have four wheel drive .

Activity 2: Any student can register project if he has passed following two subjects:
1. Operating System
2. SAD2
Write a clips program that displays a message that Ahmed can register the project if he has
passed above two subjects.

Activity 3: any one can take the license if he completes the following three conditions. His
age must be 21 years old, gender should be male and have driving license.

Learning outcome:
understand the role of AND, OR operator and using them in CLIPS programming.

How to use NOT operator in CLIPS?

Q: From the following cars find out which one is not four-wheel drive?
1. Corolla
2. Land-cruiser
3. Yukon
4. Crown-victoria
5. Camry
Step 1: Define variables
(assert (car corolla))
(assert (car land-cruiser))
(assert (car Yukon))

IS Lab Manual - 2015 12


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (car crown-victoria))


(assert (car camry))
(assert (four-wheel land-cruiser))
(assert (four-wheel Yukon))
Step 2: Rule
(defrule one
(car ?name)
(not (four-wheel ?name))
=>
(printout t ?name " is not four-wheel drive car" crlf))

Exercise 1:
Assert the below list of animals and assert the name of animals which give
egg. Define a rule to find the animals which do not give egg and display them
as mammal.
1. Monkey
2. Chicken
3. Duck
4. Camel
5. Sheep

Exercise 2:
From the following students find out the names and enter them in the
memory which is Fail?
1. Usman
2. Tariq
3. Mohammad (Pass)
4. Yahya

IS Lab Manual - 2015 13


Department of Information Systems ‫قسم نظم المعلومات‬

5. Fahad (Pass)
6. Ali (Pass)

Use of AND operator in CLIPS?

Activity 2:
Any student can register project if he has passed following two subjects:
1. Operating System
2. SAD2
Write a clips program that displays a message that Ahmed can register the
project if he has passed above two subjects.

(assert (name ahmad))


(assert (pass os))
(assert (pass sad2))
(defrule five
(name ?name)
(and (pass os)
(pass sad2))
=>
(printout t ?name "can register the project" crlf))

Activity 3:
any one can take the license if he completes the following three conditions. His
age must be 21 years old, gender should be male and have driving license.
Solution:
(assert (name ali))

IS Lab Manual - 2015 14


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (gender male))


(assert (age 21))
(assert (have license))
(defrule three
(name ?name)
(and (gender male)
(age 21)
(have license))
=>
(printout t ?name "can drive the car" crlf))

Exerciese 3: Write the following program where you can see the
conditions are not true so the rule will not execute.
Second Try (First reset your memory and type the follwoing
(assert (name ali))
(assert (pass os))
(assert (fail sad2))
(defrule six
(name ?name)
(and (pass os)
(pass sad2))
=>
(printout t ?name "can register the subject" crlf))

IS Lab Manual - 2015 15


Department of Information Systems ‫قسم نظم المعلومات‬

Exercise 4:
(assert (name ali))
(assert (car-time two-months))
(assert (car-milage 2500))
RULE:
(defrule seven
(name ?name)
(or (car-time three-months)
(car-milage 2500))
=>
(printout t ?name " car is required service" crlf))

IS Lab Manual - 2015 16


Department of Information Systems ‫قسم نظم المعلومات‬

Lab 5
Objective:
To implement and use AND operator and OR operator together in CLIPS.

Activities:
Activity 1: Write a rule in CLIPS which choose people who have a bachelor degree or a
diploma with five years of experience.

Learning outcome:
Learn to combine multiple logical operators.

Activity 1:
You can get job if you are Bachelors in Computer Science (BCS) or you have
diploma with 5 years' experience.
Question:
Tariq has diploma and has 3 years’ experience. Fahad has bachelors in
computer science. Which of them will get the job?
Solution:
For Tariq:
(assert (name tariq))
(assert (have diploma))
(assert (exp 3yrs))
(defrule seven
(name ?name)
(or (have bachlors)
(and (have diploma)
(exp 5yrs)))
=>

IS Lab Manual - 2015 17


Department of Information Systems ‫قسم نظم المعلومات‬

(printout t ?name "can take the job" crlf))


For Fahad:
(assert (name fahd))
(assert (have bachelors))
(defrule seven
(name ?name)
(or (have bachlors)
(and (have diploma)
(exp 5yrs)))
=>
(printout t ?name "can take the job" crlf))

Exercise:
Assert 10 students data with courses completed and credits left. Write rule to
print the list of students who can register for project. The condition for
registering project is completed the courses 362ISM and 326ISM or the
credits left is less than 30.

IS Lab Manual - 2015 18


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 6
Objective:
Understand the test (comparison) operation in CLIPS.

Activities:
Activity 1: Find the larger of two numbers in Clips using test operation.
Activity 1: Find the smaller of two numbers in Clips using test operation.

Learning outcome:
the use of test (comparison) operation in various mathematical operations in CLIPS

Activity 1:
Find the larger of two numbers in Clips using test operation
(assert (number 76))
(assert (number 85))
Define the rule:
(defrule ten
(number ?x)
(number ?y)
(test (> ?x ?y))
=>
(printout t ?x "is greater than" ?y crlf))

IS Lab Manual - 2015 19


Department of Information Systems ‫قسم نظم المعلومات‬

Activity 2:
Find the smaller of two numbers in Clips using test operation
(assert (number 67))
(assert (number 58))
Define the rule:
(defrule less
(number ?x)
(number ?y)
(test (< ?x ?y))
=>
(printout t ?x "is greater than" ?y crlf))

Exercise:
1. Write a CLIPS program to find greater number from 3 numbers

2. Write a CLIPS program to find smaller number from 3 numbers

IS Lab Manual - 2015 20


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 7

Objective:
Understand the representation of mathematical expressions in CLIPS.

Activities:
Activity 1: Convert the given mathematical expressions and use them in CLIPS.

Learning outcome:
Learn to represent mathematical expressions in CLIPS

How to write mathematical expressions in CLIPS?


5+7 (+ 5 7)
8*6 (* 8 6)
10/2 (/ 10 2)
47-5 (- 47 5)
2 * (5 +7) (* 2 (+ 5 7))
6+4*2 (+ 6 (* 4 2))
((10 + (4 * 19)) – (35/12)) (- (+ 10 (* 4 19)) (/ 35 12))

The Instructor must explain prefix, postfix, infix methods of expression and
the conversion method.

IS Lab Manual - 2015 21


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 8

Objective:
Understand various functions that operates on strings in CLIPS.

Activities:
Activity 1: Practice all string related operations in CLIPS.

Learning outcome:
Learn string operations in CLIPS

Working on Strings
1 String Concatenation

The strcat function will concatenates its arguments into a single string.

Syntax

(str-cat <expression>*)

Each <expression> should be one of the following types: symbol, string, float, integer, or
instance- name.

Example

CLIPS> (str-cat "foo" bar)

"foobar"

CLIPS>

IS Lab Manual - 2015 22


Department of Information Systems ‫قسم نظم المعلومات‬

2 Symbol Concatenation

The symcat function will concatenate its arguments into a single symbol. It is functionally
identical to the str- cat function with the exception that the returned value is a symbol and
not a string.

Syntax

(sym-cat <expression>*)

Each <expression> should be one of the following types: symbol, string, float, integer, or
instance- name.

3 Taking a String Apart

The substring function will retrieve a portion of a string from another string.

Syntax

(sub-string <integer-expression> <integer-expression>

<string-expression>)

where the first argument, counting from one, must be a number marking the beginning
position in the string and the second argument must be a number marking the ending
position in the string. If the first argument is greater than or equal to the second argument,
a null string is returned.

Example

CLIPS> (sub-string 3 8 "abcdefghijkl")

"cdefgh"

CLIPS>

4 Searching a String

The strindex function will return the position of a string inside another string.

Syntax

(str-index <lexeme-expression> <lexeme-expression>)

IS Lab Manual - 2015 23


Department of Information Systems ‫قسم نظم المعلومات‬

where the second argument is searched for the first occurrence of the first argument. The
str- index function returns the integer starting position, counting from one, of the first
argument in the second argument or returns the symbol FALSE if not found.

Example

CLIPS> (str-index "def" "abcdefghi")

CLIPS> (str-index "qwerty" "qwertypoiuyt")

CLIPS> (str-index "qwerty" "poiuytqwer")

FALSE

CLIPS>

5 Evaluating a Function within a String

The eval function evaluates the string as though it were entered at the command prompt.

Syntax

(eval <string-or-symbol-expression>)

where the only argument is the command, constant, or global variable to be executed.
NOTE: eval does not permit the use of local variables (except when the local variables are
defined as part of the command such as with an instance query function), nor will it
evaluate any of the construct definition forms (i.e., defrule, deffacts, etc.). The return value
is the result of the evaluation of the string (or FALSE if an error occurs).

The eval function is not available for binary-load only or run- time CLIPS configurations
(see the Advanced Programming Guide).

Example

CLIPS> (eval "(+ 3 4)")

IS Lab Manual - 2015 24


Department of Information Systems ‫قسم نظم المعلومات‬

CLIPS> (eval "(create$ a b c)")

(a b c)

CLIPS>

6 Evaluating a Construct within a String

The build function evaluates the string as though it were entered at the command prompt.

Syntax

(build <string-or-symbol-expression>)

where the only argument is the construct to be added. The return value is TRUE if the
construct was added (or FALSE if an error occurs).

The build function is not available for binary-load only or run- time CLIPS configurations
(see the Advanced Programming Guide).

Example

CLIPS> (clear)

CLIPS> (build "(defrule foo (a) => (assert (b)))")

TRUE

CLIPS> (rules)

foo

For a total of 1 rule.

CLIPS>

7 Converting a String to Uppercase

The uppercase function will return a string or symbol with uppercase alphabetic
characters.

Syntax

(upcase <string-or-symbol-expression>)

Example

IS Lab Manual - 2015 25


Department of Information Systems ‫قسم نظم المعلومات‬

CLIPS> (upcase "This is a test of upcase")

"THIS IS A TEST OF UPCASE"

CLIPS> (upcase A_Word_Test_for_Upcase)

A_WORD_TEST_FOR_UPCASE

CLIPS>

8 Converting a String to Lowercase

The lowcase function will return a string or symbol with lowercase alphabetic characters.

Syntax

(lowcase <string-or-symbol-expression>)

Example

CLIPS> (lowcase "This is a test of lowcase")

"this is a test of lowcase"

CLIPS> (lowcase A_Word_Test_for_Lowcase)

a_word_test_for_lowcase

CLIPS>

9 Comparing Two Strings

The strcompare function will compare two strings to determine their logical relationship
(i.e., equal to, less than, greater than). The comparison is performed character- by-
character until the strings are exhausted (implying equal strings) or unequal characters are
found. The positions of the unequal characters within the ASCII character set are used to
determine the logical relationship of unequal strings.

Syntax

(str-compare <string-or-symbol-expression>

<string-or-symbol-expression>)

IS Lab Manual - 2015 26


Department of Information Systems ‫قسم نظم المعلومات‬

This function returns an integer representing the result of the comparison (0 if the strings
are equal, < 0 if the first argument < the second argument, and > 0 if the first argument >
the second argument).

Example

CLIPS> (< (str-compare "string1" "string2") 0)

TRUE ; since "1" < "2" in ASCII character set

CLIPS> (str-compare "abcd" "abcd")

CLIPS>

10 Determining the Length of a String

The strlength function returns the length of a string as an integer.

Syntax

(str-length <string-or-symbol-expression>)

Example
CLIPS> (str-length "abcd")
4
CLIPS> (str-length xyz)
3

IS Lab Manual - 2015 27


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 9
Objective:
Understand the implementation of the combination of logical and mathematical operations
in CLIPS.

Activities:
Activity 1: Toyota Company offers the first service on either of the two following
conditions:
3 months from the car purchase
OR
3000KM milage
Question: Ali has purchase a new car from Toyota and in two months he complete
4000KM? Does he require service?

Learning outcome:
Learn implementation of the combination of logical and mathematical operations in CLIPS.

Activity 1
Toyota Company offers the first service on either of the two following
conditions:
3 months from the car purchase
OR
3000KM milage
Question: Ali has purchase a new car from Toyota and in two months he
complete 4000KM? Does he require service?
Solution:
(assert (name ali))
(assert (months 2))
(assert (milage 4000))

IS Lab Manual - 2015 28


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (req-milage 3000))


Rule 1:
(defrule one
(milage ?x)
(req-milage ?y)
(test (> ?x ?y))
=>
(assert (B)))
RUN the rule and check the FACTS

Rule 2:
(defrule two
(name ?name)
(or (months 3)
(B))
=>
(printout t ?name "car required service" crlf))

IS Lab Manual - 2015 29


Department of Information Systems ‫قسم نظم المعلومات‬

Exercise:
Question-1:
King Khalid University has a job. To get this job you must have Masters in
computer science AND 5 years’ experience AND age should be more than 25.
Tariq has Masters in computer science with 3 years’ experience. His age is 27
Can he get this job?

Question-2:
To register the project either the students remaining credit should be less
than 35 OR he has passed the following two subjects.
 Multimedia

 Operating Systems

Mohammad is a student whose remaining credits are 30. Can he register the
project?

IS Lab Manual - 2015 30


Department of Information Systems ‫قسم نظم المعلومات‬

Question-3:
Albayan offer the guarantee of any car up to 100000 KM within 5 years from
date of purchase.
Ahmed purchases his car in 2008 and his car current mileage is 90000 KM.
Can he use his guarantee?
Solution:
(assert (name ahmed))
(assert (pur-year 2008))
(assert (milage 90000))
(assert (req-pur-year 2011))
(assert (req-milage 100000))

(defrule one
(pur-year ?x)
(req-pur-year ?y)
(test (> ?x ?y))
=>
(assert (A)))

(defrule two
(milage ?x)
(req-milage ?y)
(test (< ?x ?y))
=>
(assert (B)))

IS Lab Manual - 2015 31


Department of Information Systems ‫قسم نظم المعلومات‬

(defrule three
(name ?name)
(and (A) (B))
=>
(printout t ?name “can use guarantee” crlf))

IS Lab Manual - 2015 32


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 10

Objective:
Understand the use of wildcards in CLIPS. Single- and Multi-field wild cards.

Activities:
Activity 1: Define some multi-field facts and use Single- and Multi-field wild cards to
display them in different way.

Learning outcome:
Learn use of wildcards in CLIPS. Single- and Multi-field wild cards.

Insert the following variables:


(assert (class IS raja ashique ashar))
(assert (class KBS ashique moiz))
(assert (class DBMS hashim ameen))
Define the following rules:
Rule 1:
(defrule cls
(class ?name $?)
=>
(printout t "there is class called " ?name crlf))
Execute the rule and see the output.

Rule 2:
(defrule cls
(class ?name $? ?member $?)
=>
(printout t ?member " is a teacher of " ?name crlf))

IS Lab Manual - 2015 33


Department of Information Systems ‫قسم نظم المعلومات‬

Execute the rule and see the output.


Exercise:
34, 23, 21, 33, 45, 78, 56, 32, 19, 98, 44, 42, 52, 12, 22, 49
From the above given room numbers assign the Odd room numbers for theory
and Even room numbers for practical.

CLIPS has two wildcard symbols that may be used to match fields in a pattern.
CLIPS interprets these wildcard symbols as standing in place of some part of a
pattern entity. The single-field wildcard, denoted by a question mark
character (?), matches any value stored in exactly one field in the pattern
entity. The multi-field wildcard, denoted by a dollar sign followed by a
question mark ($?), matches any value in zero or more fields in a pattern
entity. Single-field and multi-field wildcards may be combined in a single
pattern in any combination. It is illegal to use a multifield wildcard in a single
field slot of a deftemplate or object pattern. By default, an unspecified single-
field slot in a deftemplate/object pattern is matched against an implied single-
field wildcard. Similarly, an unspecified multifield slot in a deftemplate/object
pattern is matched against an implied multifield-wildcard.

IS Lab Manual - 2015 34


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 11

Objective:
Understand the forward chaining mechanism used for inference in knowledge-Based
Systems.

Activities:
Activity 1: Define facts and rules for a small expert system. Watch the facts and variables to
understand forward chaining algorithm.

Learning outcome:
Understand the forward chaining algorithm.

Forward Chaining(FC): Algorithm

Step 1: Consider the initial facts and store them in working memory of the
knowledge base

Step 2: Check the antecedents part(left side) of the production rules.

Step 3: If all the conditions are matched, fire the rule (execute the right side)

Step 4: If there is only one rule, do the following:

Step 4.1: Perform necessary actions.

Step 4.2: Modify working memory and update facts.

Step 4.3: Check for new conditions

Step 5: If more than one rule is selected, use the conflict resolution strategy to
select the most appropriate rules and go to Step 4.

Step 6: Continue until an appropriate rule is found and executed

IS Lab Manual - 2015 35


Department of Information Systems ‫قسم نظم المعلومات‬

Forward Chaining Technique Example

Initially working memory has following assertions.

1. runny nose

2.temperature = 104 f

3.headache

4. cough

Rules in the Rule base are:


•R1: if (nasal congestion and viroses), then diagnose (influenza) exit
•R2: if (runny nose) then assert (nasal congestion )
•R3:if (body aches), then assert (itchiness)
•R4:if (temp>100), then assert (fever)
•R5:if (headache), then assert (itchiness)
•R6:if (fever and itchiness and cough), then assert (viroses)

Solution:

The execution is as follows:

First R2 fires, so (nasal congestion) is added to working memory.

R4 fires, so (fever) is added to working memory.

R5 fires, so (itchiness) is added to working memory.

R6 fires, so (virosis) is added to working memory.

R1 fires, diagnosing the ailment as (influenza) and exit.

Solution:

(assert (runny_nose))
(assert (temperature 104))
(assert (headache))

IS Lab Manual - 2015 36


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (cough))

(defrule R1
(logical (nasal_congestion) (virosis))
=>
(assert (influenza))
)

(defrule R2
(runny_nose)
=>
(assert (nasal_congestion))
)

(defrule R3
(bodyache)
=>
(assert (itchiness))
)

(defrule R4
(temperature ?temperature)
(test (> ?temperature 100))
=>
(assert (fever))
)

(defrule R5
(headache)
=>

IS Lab Manual - 2015 37


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (itchiness))
)

(defrule R6
(logical (fever) (itchiness) (cough))
=>
(assert (virosis))
)

Example

R1: IF A and C THEN E Given facts:

R2: IF D and C THEN F A is true

R3: IF B and E THEN F B is true

R4: IF B THEN C What can be concluded?

R5: IF F THEN G

Cycle through rules, looking for rules whose premise matches the working memory.

Working memory

A, B

R4 fires: assert new fact C A, B, C

R1 fires: assert new fact E A, B, C, E

R3 fires: assert new fact F A, B, C, E, F

R5 fires: assert new fact G A, B, C, E, F, G

Concludes everything possible from available information

IS Lab Manual - 2015 38


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 12

Objective:
Understand the encoding of knowledge/facts positionally. Create a template which can be
used by non-ordered facts to access fields of the fact by name

Activities:
Activity 1: Define a template to store the details of a patient. The template should have
slots to store name, age, weight, height and blood pressure. Store some data in the template
and defile rules to fetch data from the templates.

Learning outcome:
Learn to create template, store data in the templates and fetch data from it.

How to define a template CLIPS?


Write the following code in Clips to define the template.

(deftemplate personal-data
(slot name)
(slot age)
(slot weight)
(slot height)
(multislot blood-pressure)
)

How to enter multiple data in define template of CLIPS?


(deffacts is used to enter the multiple data)
(deffacts people
(personal-data (name Andrew) (age 20) (weight 80)
(height 188) (blood-pressure 130 80))
(personal-data (name Cyril) (age 63) (weight 70)
(height 1678) (blood-pressure 180 90)))

IS Lab Manual - 2015 39


Department of Information Systems ‫قسم نظم المعلومات‬

Note: You need to write (reset) command to enter these data in facts.
Different rules on given data?
1. Display the age of different people

(defrule print-ages
(personal-data (name ?name) (age ?age))
=>
(printout t ?name " is " ?age " years old." crlf)
)

2. Display the age and weight of different people

(defrule print-ages
(and
(personal-data (name ?name) (age ?age))
(personal-data (name ?name) (weight ?weight))
)
=>
(printout t ?name " weighs " ?weight " at " ?age " years old." crlf)
)

Exercise:
Question 1:
Define a template for the students with the following details:
Name:
ID:
Date of Birth
Level
Date of Graduation
a) Enter at least records of 7 students.

IS Lab Manual - 2015 40


Department of Information Systems ‫قسم نظم المعلومات‬

b) Define a rule that display all those student details who are in level 8 or
above
c) Define a rule that display all those students details who are going to
graduate in next 6 months

IS Lab Manual - 2015 41


Department of Information Systems ‫قسم نظم المعلومات‬

LAB 13 & 14

Objective:
To develop a small expert system that would suggest solution based on user input.

Activities:
Activity 1: Define required facts and rules required for the given expert system. Make
changes in the system as per the change in requirements

Learning outcome:
Understand the development and working of knowledge-based systems.

Activity:
Load the given expert system, run it and make changes as per the direction of the lab
instructor.

;;;======================================================
;;; Automotive Expert System
;;;
;;; This expert system diagnoses some simple
;;; problems with a car.
;;;
;;; CLIPS Version 6.0 Example
;;;
;;; To execute, merely load, reset and run.
;;;======================================================

;;****************
;;* DEFFUNCTIONS *
;;****************

(deffunction ask-question (?question $?allowed-values)


(printout t ?question)
(bind ?answer (read))
(if (lexemep ?answer)
then (bind ?answer (lowcase ?answer)))
(while (not (member ?answer ?allowed-values)) do
(printout t ?question)
(bind ?answer (read))

IS Lab Manual - 2015 42


Department of Information Systems ‫قسم نظم المعلومات‬

(if (lexemep ?answer)


then (bind ?answer (lowcase ?answer))))
?answer)

(deffunction yes-or-no-p (?question)


(bind ?response (ask-question ?question yes no y n))
(if (or (eq ?response yes) (eq ?response y))
then TRUE
else FALSE))

;;;**********************
;;;* ENGINE STATE RULES *
;;;**********************

(defrule normal-engine-state-conclusions ""


(declare (salience 10))
(working-state engine normal)
=>
(assert (repair "No repair needed."))
(assert (spark-state engine normal))
(assert (charge-state battery charged))
(assert (rotation-state engine rotates)))

(defrule unsatisfactory-engine-state-conclusions ""


(declare (salience 10))
(working-state engine unsatisfactory)
=>
(assert (charge-state battery charged))
(assert (rotation-state engine rotates)))

;;;***************
;;;* QUERY RULES *
;;;***************

(defrule determine-engine-state ""


(not (working-state engine ?))
(not (repair ?))
=>
(if (yes-or-no-p "Does the engine start (yes/no)? ")
then
(if (yes-or-no-p "Does the engine run normally (yes/no)? ")
then (assert (working-state engine normal))
else (assert (working-state engine unsatisfactory)))
else
(assert (working-state engine does-not-start))))

IS Lab Manual - 2015 43


Department of Information Systems ‫قسم نظم المعلومات‬

(defrule determine-rotation-state ""


(working-state engine does-not-start)
(not (rotation-state engine ?))
(not (repair ?))
=>
(if (yes-or-no-p "Does the engine rotate (yes/no)? ")
then
(assert (rotation-state engine rotates))
(assert (spark-state engine irregular-spark))
else
(assert (rotation-state engine does-not-rotate))
(assert (spark-state engine does-not-spark))))

(defrule determine-sluggishness ""


(working-state engine unsatisfactory)
(not (repair ?))
=>
(if (yes-or-no-p "Is the engine sluggish (yes/no)? ")
then (assert (repair "Clean the fuel line."))))

(defrule determine-misfiring ""


(working-state engine unsatisfactory)
(not (repair ?))
=>
(if (yes-or-no-p "Does the engine misfire (yes/no)? ")
then
(assert (repair "Point gap adjustment."))
(assert (spark-state engine irregular-spark))))

(defrule determine-knocking ""


(working-state engine unsatisfactory)
(not (repair ?))
=>
(if (yes-or-no-p "Does the engine knock (yes/no)? ")
then
(assert (repair "Timing adjustment."))))

(defrule determine-low-output ""


(working-state engine unsatisfactory)
(not (symptom engine low-output | not-low-output))
(not (repair ?))
=>
(if (yes-or-no-p "Is the output of the engine low (yes/no)? ")
then
(assert (symptom engine low-output))
else

IS Lab Manual - 2015 44


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (symptom engine not-low-output))))

(defrule determine-gas-level ""


(working-state engine does-not-start)
(rotation-state engine rotates)
(not (repair ?))
=>
(if (not (yes-or-no-p "Does the tank have any gas in it (yes/no)? "))
then
(assert (repair "Add gas."))))

(defrule determine-battery-state ""


(rotation-state engine does-not-rotate)
(not (charge-state battery ?))
(not (repair ?))
=>
(if (yes-or-no-p "Is the battery charged (yes/no)? ")
then
(assert (charge-state battery charged))
else
(assert (repair "Charge the battery."))
(assert (charge-state battery dead))))

(defrule determine-point-surface-state ""


(or (and (working-state engine does-not-start)
(spark-state engine irregular-spark))
(symptom engine low-output))
(not (repair ?))
=>
(bind ?response
(ask-question "What is the surface state of the points (normal/burned/contaminated)? "
normal burned contaminated))
(if (eq ?response burned)
then
(assert (repair "Replace the points."))
else (if (eq ?response contaminated)
then (assert (repair "Clean the points.")))))

(defrule determine-conductivity-test ""


(working-state engine does-not-start)
(spark-state engine does-not-spark)
(charge-state battery charged)
(not (repair ?))
=>
(if (yes-or-no-p "Is the conductivity test for the ignition coil positive (yes/no)? ")
then

IS Lab Manual - 2015 45


Department of Information Systems ‫قسم نظم المعلومات‬

(assert (repair "Repair the distributor lead wire."))


else
(assert (repair "Replace the ignition coil."))))

(defrule no-repairs ""


(declare (salience -10))
(not (repair ?))
=>
(assert (repair "Take your car to a mechanic.")))

;;;****************************
;;;* STARTUP AND REPAIR RULES *
;;;****************************

(defrule system-banner ""


(declare (salience 10))
=>
(printout t crlf crlf)
(printout t "The Engine Diagnosis Expert System")
(printout t crlf crlf))

(defrule print-repair ""


(declare (salience 10))
(repair ?item)
=>
(printout t crlf crlf)
(printout t "Suggested Repair:")
(printout t crlf crlf)
(format t " %s%n%n%n" ?item))

Exercise:
Develop a small expert system of similar kind.

IS Lab Manual - 2015 46

You might also like