Big 2 PDF
Big 2 PDF
CLIPS PROGRAMMING
• Basic Commands
• Symbols, Data Types, Syntax
• Templates, Facts, Rules
• Variables and Pattern Matching
• Basic I/O, File I/O, Built-in Functions
• Math/Logical Expressions
1
History of CLIPS
• Stands for “C Language Integrated Production
System”
• Developed at NASA (1986)
• Implemented in C
• Influenced by OPS5 and ART languages
• Initial version was only a production rule interpreter.
• Latest version is named COOL (CLIPS Object-Oriented
Language)
2
Advantages of CLIPS
Components of a
Rule-Based Expert System
Knowledge Base Working Memory
(RULES) Inference (FACTS)
Engine
Agenda
Knowledge
Explanation
Acquisition
Facility
Facility
User Interface
3
Components
of a Rule-Based Language (1)
• FACT BASE or fact list represents the initial state of
the problem. This is the data from which inferences
are derived.
• RULE BASE or Knowledge Base (KB) contains a set
of rules which can transform the problem state into a
solution. It is the set of all rules.
• CLIPS supports only forward chaining rules.
Components
of a Rule-Based Language (2)
4
Basic CLIPS Commands (1)
• (exit) to exit from CLIPS
• (clear) to clear the environment from facts,
rules, and other active definitions
• (reset) to set the fact base to its initial state
(clears existing facts; sets (initial-fact),
and all (deffacts) constructs in the
program). Perform (reset) before each
program run!
• (run) executes a program currently loaded
into the CLIPS interpreter against
currently defined rule-bases and
fact-bases. 9
5
Syntax Notation
• symbols, characters, keywords
– entered exactly as shown:
– (example)
• square brackets [...]
– contents are optional:
– (example [test])
• pointed brackets < ... >
– replace contents by an instance of that type
– (example <char>)
• star *
– replace with zero or more instances of the type
– <char>*
• plus +
– replace with one or more instances of the type
– <char>+ (is equivalent to <char> <char>* )
• vertical bar |
– choice among a set of items:
11
– true | false
12
6
Comments
• Program comments begin with a semicolon “;”.
;This is a comment example
13
EXAMPLE-1:
(defrule basic
=>
(printout t “Hello, world!” crlf)
)
7
To Make It Run
• Type the code in a file and save it (e.g. hello-world.clp)
• Start CLIPS
• Type (load “hello-world.clp”)
• When the file is loaded CLIPS will display the followings:
defining defrule basic +j
TRUE
• Type (reset)
• Type (run)
Tip:You can also use the menu or hot keys for these
commands:
^E for reset
^R for run
To exit CLIPS use the menu, ^Q or (exit)
15
EXAMPLE
(defrule is-it-a-duck (defrule duck
(animal-has webbed-feet) (animal-is duck)
(animal-has feathers) =>
=> (assert (sound-is quack))
(assert (animal-is duck))) (printout t "It is a duck!" crlf))
8
A PROLOG PROGRAM
%% Facts:
father(tom, john). %% tom is father of john
mother(susan, john). %% susan is mother of john
father(george, tom). %% george is father of tom
%% Rules:
parent(X, Y) :- father(X, Y) , mother(X, Y).
grandparent(X, Z) :- parent(X, Y) , parent(Y, Z).
grandfather(X, Z) :- father(X, Y) , parent(Y, Z).
grandmother(X, Z) :- mother(X, Y) , parent(Y, Z).
17
?- consult (ornek.pl).
Yes
?- parent(A, B).
A = tom
B = john ;
A = george
A PROLOG B = tom ;
SESSION A = susan
B = john ;
?- grandparent(A, B).
A = george
B = john ;
?- grandfather(A, B).
A = george
B = john ;
18
?-
9
A CLIPS PROGRAM
; Facts:
(deffacts families
(father tom john) ; tom is father of john
(mother susan john) ; susan is mother of john
(father george tom)) ; george is father of tom
; Rules:
(defrule parent-rule
(or (father ?x ?y) (mother ?x ?y))
=>
(assert (parent ?x ?y)))
(defrule grandparent-rule
(and (parent ?x ?y) (parent ?y ?z))
=>
(assert (grandparent ?x ?z)))
(defrule grandfather-rule
(and (father ?x ?y) (parent ?y ?z))
=>
(assert (grandfather ?x ?z)))
19
CLIPS> (reset)
CLIPS> (run)
A CLIPS CLIPS> (facts)
10
Fields
• There are seven data types (types of tokens) called fields in
CLIPS.
– float: [+\-] <digit>* [.<digit>*] [e|E[+|-]<digit>*]
– integer: [+|-] <digits> *
– symbol: <char>+
– string: “<char>* “ (e.g. “John”, “848-3000”)
– external address
– instance name
– instance address
Expressions (1)
• Examples of valid words
– computer
– emergency-fire
– activate_sprinkler_system
– shut-down-electrical-junction-387
– !?#$^*
• CLIPS is case-sensitive
–Computer, COMPUTER, Computer are all different
22
11
Expressions (2)
• Examples of valid strings
– “Activate the sprinkler system.”
– “Shut down electrical junction 387.”
– “!?#$^”
– “<-;( ) +-”
• Valid numbers
– 1 1.5 .7 +3 -1 65 3.5e10 23
Facts
Fact is a chunk of information consisting of a relation
name, zero or more slots and slot values.
Examples:
(Fire)
(speed 50 km)
(cost 78 dollars 23 cents)
(pers-name “Shahram Rahimiş”)
(person (name “John Dıllards”) (age 24))
(person (name “Raheel Ahmad”) (age 25))
24
12
Fact examples
• Example 1 Example 2
– (fire) - (emergency-fire)
– (flood) - (emergency-flood)
– (Tuesday) - (day-Tuesday)
– (Wednesday) - (day-Wednesday)
25
13
Initial Facts
• deffacts used to define initial groups of facts.
• Facts from (deffacts) are automatically asserted using
(reset) command.
27
Example:
(deffacts status “Some facts about the emergency”
(emergency fire)
(fire-class A)
(fire-class B))
Facts entered using deffacts are automatically asserted
with (reset) command.
CLIPS> (reset)
CLIPS> (facts)
f-0 (initial-fact)
f-1 (emergency fire)
f-2 (fire-class A)
f-3 (fire-class B)
CLIPS>
28
14
IDENTICAL FACTS:
EXAMPLE-2:: Identical
facts can be defined in
EXAMPLE-1: By default, identical deffacts.However, only one
facts are not allowed. of them is put on working
memory.
CLIPS> (reset)
CLIPS> (assert (name Shahram)) CLIPS> (deffacts isimler
<Fact-1> (name Shahram)
CLIPS> (assert (name Shahram)) (name Shahram))
FALSE CLIPS> (reset)
CLIPS> (facts) CLIPS> (facts)
f-0 (initial-fact) f-0 (initial-fact)
f-1 (name Shahram) f-1 (name Shahram)
For a total of 2 facts. For a total of 2 facts.
29
30
15
Example:
Instead of deffacts, facts can be saved and loaded to/from a seperate fact file.
CLIPS> (load-facts "names.dat")
“names.dat” file CLIPS> (facts)
f-0 (student George)
(student George)
f-1 (student James)
(student James)
f-2 (teacher Martin)
(teacher Martin)
For a total of 3 facts.
CLIPS> (assert (teacher Peter))
<Fact-3>
“names.dat” file CLIPS> (facts)
f-0 (student George)
(student George) f-1 (student James)
(student James) f-2 (teacher Martin)
(teacher Martin) f-3 (teacher Peter)
(teacher Peter) For a total of 4 facts.
31
CLIPS> (save-facts "names.dat")
32
16
(deftemplate) Example
CLIPS> (deftemplate course “course informationş”
(slot number)
(slot name))
CLIPS> (assert (course (number CS420)
(name “Distributed Computing”))
(course (number CS401)
(name “Computer Architecture”)))
CLIPS> (facts)
f-0 (course (number CS420) (name “Distributed Computing”))
f-1 (course (number CS401) (name “Computer Architecture”)))
For a total of 2 facts
CLIPS> (retract 1)
CLIPS> (facts)
f-0 (course (number CS420) (name “Distributed Computing”))
For a total of 1 fact
33
34
17
Modifying Facts
To modify a fact:
(modify <fact-index> <slot-modifier>*)
<slot-modifier> is (<slot-name> <slot-value>)
Example:
CLIPS> (modify 0 (number CS520))
CLIPS> (facts)
f-0 (course (number 520) (name “Distributed Computing”))
for a total of 1 fact
35
Duplicating Facts
To create a duplicate of a fact:
Example:
CLIPS> (duplicate 0 (number CS420))
<fact-1>
CLIPS> (facts)
f-0 (course (number CS520) (name “Distributed Computing”))
f-1 (course (number CS420) (name “Distributed Computing”))
For a total of 2 facts
36
18
Retracting Facts
37
(deftemplate) as a record
• Templates can be extended to hold more information like records:
• Example:
(deftemplate student “a student record”
(slot name (type STRING))
(slot age (type NUMBER) (default 18)))
38
19
Example
• After the template declaration and adding:
(deffacts students
(student (name John))
(student (name Steve) (age 19)))
Ordered Facts
• Ordered facts
– Relation name with no corresponding
deftemplate
– Have single, implied multifield slot
– Implied deftemplate automatically created
– E.g., (number-list 7 9 3 4) ==
(deftemplate number-list (multislot values))
(number-list (values 7 9 3 4))
1
Rules (1)
• Syntax:
(defrule <rule-name> [<comment>]
[<declaration>] ; salience
<patterns>* ; LHS, premises, patterns,
; conditions, antecedent
=>
<actions>*) ; RHS, actions, consequent
2
Rules (2)
• Example:
(defrule emergency-type-earthquake
(emergency earthquake)
=>
(printout t “There is a earthquake!” crlf))
41
Rule Components
• rule header
– defrule keyword, name of the rule, optional comment string
• rule antecedent (LHS)
– patterns to be matched against facts
• rule arrow
– separates antecedent and consequent
• rule consequent (RHS)
– actions to be performed when the rule fires
42
21
Properties of Simple Rules
• very limited:
– LHS must match facts exactly
– facts must be accessed through their index number
– changes must be stated explicitly
• can be enhanced through the use of variables
43
Variables (1)
22
Variables (2)
• variables
– symbolic name beginning with a question mark "?"
– variable bindings
• variables in a rule pattern (LHS) are bound to the corresponding
values in the fact, and then can be used on the RHS
• all occurrences of a variable in a rule have the same value
• the left-most occurrence in the LHS determines the value
• bindings are valid only within one rule
– access to facts
• variables can be used to make access to facts more convenient:
?age <- (age harry 17)
45
Variable Example
(defrule grandfather
(is-a-grandfather ?name)
=>
(assert (is-a-father ?name))
(assert (is-a-man ?name))
(printout t ?name “ is a grandfather” crlf)
)
46
23
Example
(deffacts animal-fact-base This program will
(animal dog) produce the following
(animal cat) results:
(animal duck)
(animal turtle)) CLIPS>(reset)
CLIPS>(run)
(defrule list-animals turtle found
(animal ?name) duck found
=> cat found
(printout t ?name " found" crlf)) dog found
CLIPS>
47
(defglobal
?*income* = 250000
?*name* = “John Lambert"
)
48
24
Fact Address
• To remove a fact from the fact-list use (retract)
• Before a fact can be retracted it must be specified to CLIPS by its
index.
• Rules can be used to modify the fact base. To achieve it variables
have to be bound to fact addresses using ‘<-’:
?num <- (course (number ?cmp))
• This appears in the LHS of the rule, and can be referred to in
either LHS and RHS.
• Example:
(defrule remove-grandfather-fact
?adr <- (is-a-grandfather Jamie)
=>
(retract ?adr)) 49
Wildcards (1)
To specify a general pattern we can use wildcards:
• For single field variables: wildcard ?
• For multifield variables (zero or more) wildcard $?
Examples:
(courses (numbers $?course_nums))
(printout t “Your courses are” $?course_nums crlf))
(list ? $? c ?)
– can match these:
(list a b f c e), (list a d c b)
– but not these:
(list c), (list c d), (list a c d b)
50
25
Wildcards (2)
• The fact
(do picnic on Sunday)
• will match any of the following
– (do ? ? Sunday)
– (do ? on ?)
– (do ? on ?when)
– (do $? )
– (do $? Sunday)
– (do ?chore $?when)
51
EXAMPLE: Usage of $?
(deffacts ESFact
(ES gives soul to programs))
(defrule R-3
(ES ? $?what2)
=>
(printout t "$?what2: " $?what2 crlf ))
52
26
Retracting Facts Using Wildcards
(defrule change-grandfather-fact
?old-fact <- (is-a-grandfather ?name)
=>
(retract ?old-fact)
(assert (has-a-grandchild ?name)
(is-a-man ?name))
)
• You can retract several facts:
(retract ?fact1 ?fact2 ?fact3)
• Or you can retract all of them at once:
(retract *)
53
To Display Constructs
• To display constructs:
(list-defrules)
(list-deftemplates)
(list-deffacts)
• To display the text of definitions of the constructs:
(ppdefrule <defrule-name>)
(ppdeftemplate <deftemplate-name>)
(ppdeffeacts <deffacts-name>)
54
27
To Delete Constructs
(undefrule <defrule-name>)
(undeftemplate <deftemplate-name>)
(undeffacts <deffacts-name>)
55
•
Manipulation of Constructs
show list of constructs
(list-defrules)
(list-deftemplates)
(list-deffacts)
• prints a list of the respective constructs
• show text of constructs
(ppdefrule <defrule-name>)
(ppdeftemplate <deftemplate-name>)
(ppdeffacts <deffacts-name>)
• displays the text of the construct (``pretty print'')
• deleting constructs
(undefrule <defrule-name>)
(undeftemplate <deftemplate-name>)
(undeffacts <deffacts-name>)
• deletes the construct (if it is not in use)
• clearing the CLIPS environment
(clear)
removes all constructs and adds the initial facts to the CLIPS environment 56
28
Field Constraints
57
29
Example: Agriculture
Problem Description: Write a CLIPS program that is capable of
recommending a herbicide and the appropriate application rate for
that herbicide for a given field situation. Information concerning
the herbicides and their application guidelines are contained in the
following table. The crops are corn (C) and soybeans (S) and the
weeds are grass (G) and broadleaf (B).
Organic Matter
(defrule Sencor-1
(weed B)
(crop C | S)
(organic-matter 1)
=>
(printout t crlf "Do not use Sencor!" crlf))
(defrule Sencor-2
(weed B)
(crop C | S)
(organic-matter 2 | 3)
=>
(printout t crlf "Use 3/4 pt/ac of Sencor" crlf))
(defrule Lasso-1
(weed B | G)
(crop C | S)
(organic-matter 1)
=>
(printout t crlf "Use 2 pt/ac of Lasso" crlf))
60
30
(defrule Lasso-2
(weed B | G)
(crop C | S)
(organic-matter 2)
=>
(printout t crlf "Use 1 pt/ac of Lasso" crlf))
(defrule Lasso-3
(weed B | G)
(crop C | S)
(organic-matter 3)
=>
(printout t crlf "Use 0.5 pt/ac of Lasso" crlf))
(defrule Bicep-1
(weed B | G)
(crop C)
(organic-matter 1)
=>
(printout t crlf "Use 1.5 pt/ac of Bicep" crlf))
61
(defrule Bicep-2
(weed B | G)
(crop C)
(organic-matter 2)
=>
(printout t crlf "Use 2.5 pt/ac of Bicep" crlf))
(defrule Bicep-3
(weed B | G)
(crop C)
(organic-matter 3)
=>
(printout t crlf "Use 3 pt/ac of Bicep" crlf))
62
31
(defrule input
(initial-fact)
=>
(printout t crlf "What is the crop? (C: corn, S: soybean) ")
(assert (crop =(read))) ;this line reads what the user types
(printout t crlf "What is the weed problem? (B: broadleaf, G: grass) ")
(assert (weed =(read)))
(printout t crlf "What is the percentage of organic matter content?
(1: <2%, 2: 2-4%, 3: > 4%) ")
(assert (organic-matter =(read)))
(printout t crlf "RECOMMENDATIONS:" crlf))
63
RECOMMENDATIONS:
Use 3/4 pt/ac of Sencor
Use 1 pt/ac of Lasso
Use 2.5 pt/ac of Bicep
CLIPS> (dribble-off)
64
32
Math Expressions
Mathematical Operators
• basic operators (+,-,*,/) and many functions
(trigonometric, logarithmic, exponential) are supported
• prefix notation
• no built-in precedence, only left-to-right and parentheses
• test feature
– evaluates an expression in the LHS instead of matching a pattern
against a fact
• pattern connectives
– multiple patterns in the LHS are implicitly AND-connected
– patterns can also be explicitly connected via AND, OR, NOT
• user-defined functions
– external functions written in C or other languages can be integrated
66
33
Pattern Logical OR (1)
Suppose the following three rules are given.
(defrule shut-off-electricity-1
(emergency flood)
=>
(printout t “Shut off the electricity” crlf))
(defrule shut-off-electricity-2
(disaster C)
=>
(printout t “Shut off the electricity” crlf))
(defrule shut-off-electricity-3
(sprinkler-systems active)
=>
(printout t “Shut off the electricity” crlf))
67
(defrule shut-off-electricity
(or (emergency flood)
(disaster C)
(sprinkler-systems active))
=>
(printout t “Shut off the electricity” crlf))
68
34
Pattern Logical AND
• It is the default (implicit) operator.
• It requires that all the patterns of the LHS of the rule to
be matched to facts in order to trigger the rule.
(defrule shut-off-electricity
(and (emergency flood)
(disaster C)
(sprinkler-systems active))
=>
(printout t “Shut off the electricity” crlf))
69
(defrule no-emergency
(report-status)
(not (emergency ?))
=>
(printout t “No emergency being handled” crlf))
70
35
Universal Conditional Elements
71
(deftemplate person
(slot name) (slot age) (slot height))
(deffacts people
(person (name Andrew) (age 24) (height 1.85))
EXAMPLE-1: (person (name Cyril) (age 23) (height 1.70))
(person (name James) (age 20) (height 1.72))
(no conditions) (person (name Albert) (age 19) (height 1.80)))
(defrule check-each-person
(person (name ?n))
=>
(printout t "All persons have a name data" crlf))
36
EXAMPLE-2:
(includes forall condition)
(defrule check-each-person
(forall (person (name ?n))
(person (name ?n))
)
=>
(printout t "All persons have a name data" crlf))
EXAMPLE-3:
(includes exists condition)
(defrule any-people
(exists (person (name ?n)))
=>
(printout t "There is at least one person with a name" crlf)
)
37
Test Control Pattern
75
EXAMPLE
(deffacts people
(person (name Andrew) (age 24) (height 1.85))
(person (name Jane) (age 23) (height 1.70)))
(defrule display-tall-persons
(person (name ?esm) (height ?gad))
(test (> ?gad 1.80))
=>
(printout t ?esm " height is " ?gad crlf)
)
76
38
Predicate Functions
• The predicate functions are used to return a value of either
true or false - and, not, or
• eq equal, neq not equal
(eq <any-value> <any-value>)
• = equal, != not equal, >= greater than or equal,
> greater than, <= less than or equal, < less than These
are used for numeric values.
(<= <numeric-value><numeric-value>)
• These are used to test the type of a field:
numberp, stringp, wordp, integerp, evenp,
oddp
77
39
SWITCH Function
(defrule start
=>
(printout t crlf crlf crlf)
(printout t " **********************************" crlf)
(printout t " * List of your choices *" crlf)
(printout t " * Choose one *" crlf)
(printout t " **********************************" crlf)
(printout t " * 1.Your First Choice *" crlf)
(printout t " * 2.Your Second Choice *" crlf)
(printout t " * 3.Your Third Choice *" crlf)
(printout t " * 4.Stop Rules Execution *" crlf)
(printout t " **********************************" crlf)
(printout t " Your choice? ")
(bind ?menu (read))
(switch ?menu (defrule one
(case 1 then (choice one)
(assert (choice one))) =>
(case 2 then (printout t crlf "This is your first choice:..." crlf))
(assert (choice two)))
(case 3 then (defrule two
(assert (choice three))) (choice two)
(case 4 then =>
(printout t crlf "stoping..." crlf) (printout t crlf "This is your second choice:..." crlf))
(halt))
(default then (defrule three
(printout t crlf "What did you choose?" crlf) (choice three)
(reset) =>
(run)))) (printout t crlf "This is your third chocie:..." crlf))
79
LOOP-FOR-COUNT Function
(defrule factorial
=>
(printout t crlf crlf "Enter a number: ")
(bind ?N (read))
(bind ?temp 1)
(loop-for-count (?i 1 ?N) do
(bind ?temp (* ?temp ?i))
)
(printout t "Factorial=" ?temp crlf)
)
80
40
Implicit Looping Example
(deffacts initial-information
(rectangle 10 6)
(rectangle 7 5)
(rectangle 6 8)
(rectangle 2 5)
(rectangle 9 4)
(sum 0)
(count 0))
(defrule sum-rectangles
(declare (salience 30))
(rectangle ?height ?width)
=>
(assert (add-to-sum = (* ?height ?width))))
81
(defrule sum-areas
(declare (salience 20))
?sum-adr <- (sum ?total)
?new-area-adr <- (add-to-sum ?area)
?count-adr <- (count ?counter)
=>
(retract ?sum-adr ?new-area-adr ?count-adr)
(assert (sum = (+ ?total ?area)))
(assert (count = (+ ?counter 1))))
(defrule average
(declare (salience 10))
?sum-adr <- (sum ?total)
?count-adr <- (count ?counter)
=>
(printout t crlf "Here is the average area" (/ ?total ?counter) crlf crlf))
82
41
Avoiding Infinite Loop
• You can get into an infinite loop if you are not careful enough.
(deffacts myfact
(loop-fact))
(defrule simple-loop
?old-fact <- (loop-fact)
=>
(printout t “Looping!” crlf)
(retract ?oldfact)
(assert (loop-fact)))
83
(defrule find-largest-number
(number ?x)
(not (number ?y &: (> ?y ?x)))
=>
(printout t “Largest number is “ ?x crlf))
84
42
Defining Functions
Syntax: (deffunction function-name (arg ... arg)
action ... action)
Example:
(deffunction hypotenuse (?a ?b)
(sqrt (+ (* ?a ?a) (* ?b ?b))))
(defrule hesapla
=>
(printout t “hypotenuse for 8 and 5: “ (hypotenuse 8 5) crlf))
85
EXAMPLE:CALCULATING FACTORIAL
(deffunction factorial(?X)
(bind ?temp 1)
(loop-for-count (?i 1 ?X) do
(bind ?temp (* ?temp ?i))
)
(return ?temp)
)
(defrule example
=>
(printout t crlf crlf "N factorial: ")
(bind ?N (read))
(printout t "Factorial=" (factorial ?N) crlf)
86
)
43
Standard I/O Functions
• To print to screen: (printout t …)
For the new line use: crlf
• To read from keyboard use:(read)
• Example-1:
(defrule to-start
(phase choose-name)
=>
(printout t “Enter your name” crlf)
(assert (your-name =(read)))) ; ’=’ is optional
• Example-2:
(defrule to-start
=>
(printout t “Enter something: ”)
(bind ?something (read))
87
(printout t “You have entered ” ?something crlf))
(defrule continue-check
?phase <- (phase check-continue)
=>
(retract ?phase)
(printout t “Do you want to continue?” crlf)
(bind ?answer (read))
(if (or (eq ?answer yes) (eq ?answer y))
then (assert (phase continue))
else (halt))
)
88
44
• print information
(printout <logical-device> <print-items>*)
• logical device frequently is the standard output device t (terminal)
• terminal input
(read [<logical-device>])
(readline [<logical-device>])
• read an atom or string from a logical device
• the logical device can be a file which must be open
• open / close file
(open <file-name> <file-ID> [<mode>])
(close [<file-ID>])
• open /close file with <file-id> as internal name
• load / save constructs from / to file
(load <file-name>)
(save <file-name>)
– e.g. (load "B:\\clips\\example.clp") 89
Input Example-1
(deffacts initial-phase
(phase choose-player))
(defrule player-selection
(phase choose-player)
=>
(printout t “Who moves first? (Computer: c Human: h)”)
(assert (player-select =(read))) )
(defrule good-player-choice
?phase <- (phase choose-player)
?choice <- (player-select ?player&c|h)
=>
(retract ?phase ?choice)
(assert (player-move ?player)) ) 90
45
(defrule bad-player-choice
?phase <- (phase choose-player)
?choice <- (player-select ?player&~c&~h)
=>
(retract ?phase ?choice)
(assert (phase choose-player))
(printout t “Choose c or h.” crlf) )
91
Input Example-2
• (read) - is used to input a single field.
• It can also be used with the bind command.
(defrule continue-check
?phase <- (phase check-continue)
=>
(retract ?phase)
(printout t “Do you want to continue?” crlf)
(bind ?answer (read))
(if (or (eq ?answer yes) (eq ?answer y))
then (assert (phase continue))
else (halt) ) ) 92
46
File I/O Functions
(defrule open-files
=> indata.dat file
(open "indata.dat" indata "r")
(open "outdata.txt" outdata "w")
"Jamie Lambertş" 74
(assert (phase read-from-file))) "Norm Carve" ş 83
"Fred Petry" 45
(defrule read-data "Bill White" 80
?phase-adr <- (phase read-from-file)
=>
(retract ?phase-adr)
(bind ?name (read indata))
(if (eq ?name EOF) outdata.txt file
then (close indata)
(close outdata) Jamie Lambertş74
(halt)) Norm Carver 83 ş
(bind ?age (read indata)) Bill White 80
(if (> ?age 50)
then (printout t ?name crlf)
(printout outdata ?name " " ?age crlf))
93
(assert (phase read-from-file)))
BUILT-IN FUNCTIONS
•String Functions
•Multi-field Functions
•Math Functions
•Utility Functions
94
47
Examples of String Functions
• CLIPS> (str-assert "student 12345 \"Lisa Gandy\"ş1985")
This command asserts the following fact:
(student 12345 "Lisa Gandy"ş 1985)
• (sub-string 2 5 “Shahram”)
This command produces following output:
hahr
95
48
• (member c (mv-append a b c “red”)
This command returns the index of specified filed value:
3
97
• (min 3 1 8 7) • (mod 17 2)
1 1
•(max 3 1 8 7) •(** 3 2)
8 9
98
49
Examples of Utility Functions
•system:
(defrule list-the-directory
=>
(system “ls ” “*.txt”))
When this rule is executed, the specified UNIX file names
appear on screen:
•batch:
When we enter the following command, all commands in batch
file are executed.
CLIPS> (batch "mybatch.bat")
(load “pro1.clp”)
(load “pro2.clp”)
(reset)
(run)
99
gensym Function
Symbol generation commands generate a unique word every time called:
Example-2:
Example-1:
CLIPS>(deffacts list
CLIPS> (gensym) (name John (gensym))
gen1 (name Ken (gensym))
(name Bob (gensym)))
• CLIPS> (gensym)
gen2 CLIPS> (reset)
CLIPS> (facts)
• CLIPS> (setgen 15) f-0 (initial-fact)
• CLIPS> (gensym) f-1 (name John gen1)
gen15 f-2 (name Ken gen2)
f-3 (name Bob gen3)
• CLIPS> (gensym) For a total of 4 facts.
gen16
100
50
Agenda
101
EXAMPLE:
(deffacts myFact
(name John)
(name Ken)
(school SIUC)
(school SIUE)
)
(defrule print-names
(name ?n)
=>
(printout t ?n crlf))
(defrule print-schools
(school ?s)
=>
(printout t ?s crlf)) 102
51
CLIPS SESSION: CLIPS> (run) CLIPS> (agenda)
SIUE 0 print-names: f-5
CLIPS> (load "orn.clp") SIUC For a total of 1 activation.
Defining deffacts: factler Ken CLIPS> (run)
Defining defrule: print-names +j John Selim
Defining defrule: print-schools +j CLIPS> (facts) CLIPS> (agenda)
TRUE f-0 (initial-fact)
CLIPS> (facts) f-1 (name John)
CLIPS> (agenda) f-2 (name Ken)
CLIPS> (reset) f-3 (school SIUC)
CLIPS> (facts) f-4 (school SIUE)
f-0 (initial-fact) For a total of 5 facts.
f-1 (name John) CLIPS> (agenda)
f-2 (name Ken) CLIPS> (assert (name Selim))
f-3 (school SIUC) <Fact-5>
f-4 (school SIUE) CLIPS> (facts)
For a total of 5 facts. f-0 (initial-fact)
CLIPS> (agenda) f-1 (name John)
0 print-schools: f-4 f-2 (name Ken)
0 print-schools: f-3 f-3 (school SIUC)
0 print-names: f-2 f-4 (school SIUE)
0 print-names: f-1 f-5 (name Selim)
103
For a total of 4 activations. For a total of 6 facts.
Salience
• Salience is used to determine the order of execution of
rules (-10,000 to 10000).
• Normally the agenda acts like a stack.
• The most recent activation placed on the agenda is
the first rule to fire.
• Salience allows more important rules to stay at the top
of the agenda regardless of when they were added.
• If you do not explicitly say, CLIPS will assume the rule
has a salience of 0.
104
52
Example-1 (No salience)
(defrule kural-A
=> In this program, rules have equal
(printout t “kural-A is fired” crlf)) priorities. Therefore the following
output is generated:
(defrule kural-B
=> CLIPS> (reset)
(printout t “kural-B is fired” crlf)) CLIPS> (run)
105
106
53
Example-3 (No salience)
(deffacts gercekler
(myfact A)
(myfact B) This example is a modified
(myfact C)) version of Example-2. Instead of
asserting facts during run-time,
(defrule kural-A they are defined as initial facts in
(myfact A) this program.
=>
(printout t “kural-A is fired” crlf)) CLIPS> (reset)
CLIPS> (run)
(defrule kural-B
(myfact B) Output is the same as Example-2:
=>
(printout t “kural-B is fired” crlf)) kural-C is fired
kural-B is fired
(defrule kural-C kural-A is fired
(myfact C)
=>
(printout t “kural-C is fired” crlf)) 107
Example-4 (salience)
(defrule kural-A
(declare (salience 20))
In this program the following
=>
output is generated: Saliences
(printout t “kural-A is fired” crlf))
always enforce the firing order
between rules.
(defrule kural-B
(declare (salience 30))
CLIPS> (reset)
=>
CLIPS> (run)
(printout t “kural-B is fired” crlf))
kural-B is fired
(defrule kural-C
kural-A is fired
(declare (salience 10))
kural-C is fired
=>
(printout t “kural-C is fired” crlf))
108
54
Example-5 (salience)
(defrule kural-A Now suppose we assert the
(declare (salience 20)) following three facts in this
(myfact A) order:
=>
(printout t “kural-A is fired” crlf)) CLIPS> (reset)
CLIPS> (assert (myfact A))
(defrule kural-B CLIPS> (assert (myfact B))
(declare (salience 30)) CLIPS> (assert (myfact C))
(myfact B) CLIPS> (run)
=>
(printout t “kural-B is fired” crlf)) In this case, the order of
assertion commands does not
(defrule kural-C effect the output, because
(declare (salience 10)) saliences enforce the firing
(myfact C) order between rules.
=>
(printout t “kural-C is fired” crlf)) kural-B is fired
kural-A is fired
kural-C is fired 109
110
55
Conflict Resolution in CLIPS
• First, CLIPS uses salience to sort the rules. Then it uses the
other strategies to sort rules with equal salience.
• Rule-based expert system is opportunistic
• Some procedural aspect normal; not more than 7 level
- E.g., human’s move vs. computer’s move
111
Salience Mechanism
Detection
Isolation Salience
Recovery
112
56
Control Rules Example
(defrule detection-to-isolation
?phase <- (phase detection)
(declare (salience –10))
=>
(retract ?phase)
(assert (phase isolation)))
(defrule isolation-to-recovery
?phase <- (phase isolation)
(declare (salience –10))
=>
(retract ?phase)
113
(assert (phase recovery)))
(defrule recovery-to-detection
?phase <- (phase recovery)
(declare (salience –10))
=>
(retract ?phase)
(assert (phase detection)))
(defrule find-fault-location-and-recovery
(phase recovery)
(recovery-solution switch-device ?replacement on)
=>
(printout t “Switch device” ?replacement “on” crlf))
114
57
Separation of Expert/Domain Knowledge &
Control Knowledge
Expert Knowledge
Salience
Control Knowledge
Control
Rules
115
(defrule change-phase
(declare (salience -10))
?phase <- (phase ?current-phase)
(phase-after ?current-phase ?next-phase)
=>
(retract ?phase)
(assert (phase ?next-phase)))
116
58
It can also be written as a sequence of phases to be cycled
through
(deffacts control-information
(phase detection)
(phase-sequence isolation recovery detection))
(defrule change-phase
(declare (salience -10))
?current-adr <- (phase ?current-phase)
?phase-adr <- (phase-sequence ?next-phase $?other-phases)
=>
(retract ?current-adr ?phase-adr)
(assert (phase ?next-phase))
(assert (phase-sequence $?other-phases ?next-phase)))
117
Debugging
118
59
Commands for Debugging
Limitations of CLIPS
• single level rule sets
– you can not arrange rule sets in a hierarchy,
embedding one rule set inside another, etc
• CLIPS has no explicit agenda mechanism
– the basic control flow is forward chaining
– to implement other kinds of reasoning you have to
manipulate tokens in working memory
120
60
Alternatives to CLIPS
• JESS (Java Expert System Shell)
– has same syntax as CLIPS
– can be invoked from Java programs
– COOL is replaced by Java classes
• Eclipse
– has same syntax as CLIPS
– supports goal-driven (i.e., backwards) reasoning
– can be integrated with C++ and dBase
• NEXPERT OBJECT
– rule and object-based system
– has a script language for designing user front-end
– written in C, runs on many platforms 121
61