Você está na página 1de 51

CLIPS Tutorial 1

Introduction to CLIPS

SEG 7450

CLIPS in PC
CLIPS is a tool for building expert systems. http://clipsrules.sourceforge.net/index.html CLIPS is a multiparadigm programming language that provides support for rule-based, ob ect!oriented, and procedural programming. "ou can do#nload it from: http://sourceforge.net/pro ect/sho#files.php$group%id&'()*+( ,pac-age%id&'.//.'
0o#nload CLIPS1in.2ip 3xtract the 2ipped file.

SEG 7450

CLIPS in PC
4r accessing CLIPS in S3 laboratories through the path 566Sepc.7+6seg+*)/8

SEG 7450

CLIPS in PC
0ouble clic- the program 5CLIPS#in.exe8

SEG 7450

CLIPS in PC
Select File !9 Load to load a clips program Select Execution !9 Reset to reset memory Select Execution !9 Run to execute the program Select Execution !9 Clear CLIPS to clear the memory Select Browse !9 Deffacts Manager to list the name of deffacts construct Select Browse !9 Deftem late Manager to list the name of 0eftemplate construct Select !indow !9 Facts to list the facts in memory Select !indow !9 "genda to list the rule to be fired at the current step Select !indow !9 #lo$als 1indo# to list the globals variance
SEG 7450 5

CLIPS in PC
:o access CLIPS ;elp

SEG 7450

CLIPS in PC

SEG 7450

CLIPS in PC
Download CLIPS %&'( and its )el
3nter #eb site http://sourceforge.net/pro ect/sho#files.php$group%id&'()*+(,pac-age%id&'. //.' Select <elease ..'*( 0o#nload cli swin*executa$le*%'(1&+i =n2ip and extract CLIPS1in.exe , CLIPS..hlp to the same directory in your PC..

Download CLIPS exam les


3nter #eb site http://sourceforge.net/pro ect/sho#files.php$group%id&'()*+(,pac-age%id&'. //.' Select <elease ..'* 0o#nload and extract exam les*%'(&+i to your PC.

Download CLIPS user guide


Clic- http://clipsrules.sourceforge.net/4nline0ocs.html. >or others materials, you can visit http://clipsrules.sourceforge.net/index.html
SEG 7450 8

CLIPS Programming
Basic elements of an Ex ert S,stem
>act!list : ?lobal memory for data @no#ledge!base : Contain all the rules Inference 3ngine : Control overall execution

" rogram in CLIPS consists of


>acts <ules

SEG 7450

3ntering and 3xiting CLIPS


:he CLIPS prompt appear as follo#s: CLIPS> Commands can be entered directly to CLIPSA this mode is called the top level. The normal mode of leaving CLIPS is the exit command. (exit) 3ach CLIPS command must have a matching number of left and right parentheses. :he final step in executing a CLIPS command after it has been entered #ith properly balanced parentheses is to press the return -ey. CLIPS> (+ 3 4) 7 CLIPS> (exit)

SEG 7450

10

3ntering and 3xiting CLIPS


B symbol surrounded by parentheses is considered to be a command or function call. :he input CD 7 *E is a call to the D function. :he input CexitE invo-es the exit command.

SEG 7450

11

>ields
:o-ens represent groups of characters that have special meaning to CLIPS. :he group of to-ens -no#n as fields is of particular importance. :here are eight types of fields, also called the CLIPS primitive data types:
float, integer, symbol, string, external address, fact address, instance name, and instance address.

CLIPS is case!sensitive.

SEG 7450

12

>ields
B symbol is a field that starts #ith a printable BSCII character and is follo#ed by 2ero or more characters.
:he end of a symbol is reached #hen a delimiter is encountered. 0elimiters include any nonprintable BSCII character. Cspaces, tabs, returns, line feedsE and CE,FGHA Symbols cannot contain delimiters. 3.g.
Space! Space!Station >ire activate%sprin-ler%system

B string must begin and end #ith double Iuotation mar-s, #hich are part of the field.
3.g. Bctive the sprin-ler system.

3xternal addresses represent the address of an external data structure returned by a user!defined function. B fact address is used to refer to a specific fact. Bn instance address is li-e a fact address, but it refers to an instance rather than a fact. B series of 2ero or more fields contained together is referred to as a multi-field value. B multifield value is enclosed by left and right parentheses.
3.g.
CE Cthis thatE
SEG 7450 13

Facts
:o solve a problem, a CLIPS program must have data or information #ith #hich it can reason. B chun- of information in CLIPS is called a fact. >acts consist of a relation name follo#ed by 2ero or more slots and their associated values. :he follo#ing is an example of a fact:
(person (name "John Q. Public") (age 23) (eye-color blue) (hair-color black))

:he symbol person is the facts relation name and the fact contains four slots: name, age, eye-color, and hair-color.
:he value of the name slot is 5John K. Public8 :he value of the eye!color slot is blue. :he value of the hair!color slot is blac-.

SEG 7450

14

Facts
:he order in #hich slots are specified is irrelevant. :he follo#ing fact is treated as identical to the first person fact by CLIPS.
(person (hair-color black) (name "John Q. Public") (eye-color blue) (age 23))

SEG 7450

15

:he 0eftemplate Construct


Lefore facts can be created, CLIPS must be informed of the list of valid slots for a given relation name. ?roups of facts that share the same relation name and contain common information can be described using the deftemplate construct. :he general format of a deftemplate is:
(deftemplate <relation-name> [<optional-comment>] <slot-definition>*)

:he syntax description Gslot!definition9 is defined as:


(slot <slot-name>) | (multislot <slot-name>)

:he deftemplate for the person fact:


(deftemplate person "An example deftemplate" (slot name) (slot age) (slot eye-color) (slot hair-color))

SEG 7450

16

Multifield Slots
MuItislot -ey#ord in their corresponding deftemplates are allo#ed to contain 2ero or more values (person (name John Q. Public) (age 23 ) (eye-color blue) (hair-color brown)) is illegal if name is a single!field slot, but legal if name is a multifield slot.

SEG 7450

17

4rdered >acts
>acts #ith a relation name that does not have a corresponding deftemplate are called ordered facts. >or example, a list of numbers could be represented #ith the follo#ing fact:
(number-list 7 9 3 4 20)

:here are t#o cases in #hich ordered facts are useful. >acts consisting of ust a relation name are useful as flags and looidentical regardless of #hether a deftemplate has been defined. >or example,
(all-orders-processed)

>or facts containing a single slot, the slot name is usually synonymous #ith the relation name. >or example, the facts:
(time 8:45) (food-groups meat dairy bread fruits-and-vegetables)

are as meaningful as:


(time (value 8:45)) (food-groups (values meat dairy bread fruits-and-vegetables))
SEG 7450 18

4rdered >acts
B deftemplate fact is a non!ordered fact. 4rdered versus Non!ordered 4rdered facts encode information #ith fixed position #hich is not convenient to access Clarity and slot order independence are virtues of deftemplate facts 3xtra command Ce.g. modify, duplicateE for non!ordered facts

SEG 7450

19

0eftemplate 4vervie#

SEG 7450

20

Mani ulation of Facts -- assert


Lasic commands to operate on facts:
assert. retract. modif,. du licate. facts

"dding Facts
Ne# facts can be added to the fact list using the assert command.
(assert <fact>+)

Bs an example,
CLIPS> (deftemplate person (slot name) (slot age) (slot eye-color) (slot hair-color)) CLIPS> (assert (person (name "John Q. Public") (age 23) (eye-color blue) (hair-color black))) <Fact-0> CLIPS>
SEG 7450 21

Mani ulation of Facts -- assert


More than one fact can be asserted using a single assert command. >or example, the command: (assert (person (name "John Q. Public") (age 23) (eye-color blue) (hair-color black)) (person (name "Jane Q. Public") (age 36) (eye-color green) (hair-color red)))

SEG 7450

22

Mani ulation of Facts -- facts


Dis la,ing Facts :he facts command can be used to display the facts in the fact list. (facts) >or example, CLIPS> (facts) f-0 (person (name "John Q. Public") (age 23) (eye-color blue) (hair-color black)) For a total of 1 fact. CLIPS> 3very fact that is inserted into the fact list is assigned a uniIue fact identifier starting #ith the letter f and follo#ed by an integer called the fact index.

SEG 7450

23

Mani ulation of Facts -- facts


:he complete syntax for the facts command is: (facts [<start> [<end> [<maximum>]]])
#here Gstart9, Gend9, and Gmaximum9 are positive integers. If no arguments are specified, all facts are displayed. If the Gstart9 argument is specified, all facts #ith fact indexes greater than or eIual to Gstart9 are displayed. If Gstart9 and Gend9 are specified, all facts #ith fact indexes greater than or eIual to Gstart9 and less than or eIual to Gend9 are displayed. >inally, if Gmaximum9 is specified along #ith Gstart9 and Gend9. no more than Gmaximum9 facts #ill be displayed.

SEG 7450

24

Mani ulation of Facts -- retract


<emoving facts
<emoving facts from the fact list is called retraction and is done #ith the retract command. :he syntax of the retract command is: (retract <fact-index>+) (retract 0) B single retract command can be used to retract multiple facts at once. (retract 0 1)

SEG 7450

25

Mani ulation of Facts -- modif,


Modifying facts
Slot values of deftemplate facts can be modified using the modif, command.

(modify <fact-index> <slot-modifier>+)


#here Gslot!modifier9 is:

(<slot-name> <slot-value>)
>or example, CLIPS> (modify 0 (age 24)) <Fact-2> CLIPS> (facts) f-2 (person (name "John Q. Public") (age 24) (eye-color blue) (hair-color black)) For a total of 1 fact. CLIPS> B ne# fact index is generated for a modified fact.
SEG 7450 26

Mani ulation of Facts -- du licate


Du licating facts du licate command
CLIPS> (duplicate 2 (name "Jack S. Public)) <Fact-3> CLIPS> (facts) f-2 (person (name "John Q. Public") (age 24 ) (eye-color blue) (hair-color black)) f-3 (person (name "Jack S. Public") (age 24) (eye-color blue) (hair-color black)) For a total of 2 facts. CLIPS>

:he modify and duplicate commands cannot be used #ith ordered facts. :o enable the duplicate command, the follo#ing command may be reIuired:
(set-fact-duplication TRUE)
SEG 7450 27

Mani ulation of Facts -- watc)


:he watc) command is useful for debugging programs. (watch <watch-item>) #here G#atch!item9 is one of the symbols facts, rules, activations, statistics, compilations, focus, deffunctions, globals, generic!functions, methods, instances, slots, messages, message!handlers, or all. If facts are being #atched, CLIPS #ill automatically print a message indicating that an update has been made to the fact list #henever facts are asserted or retracted. :he effects of a watch command may be turned off by using the corresponding un#atch command. (unwatch <watch-item>)

SEG 7450

28

Mani ulation of Facts -- watc)


CLIPS> (facts 3 3) f-3 (person (name "Jack S. Public") (age 24) (eye-color blue) (hair-color black)) For a total of 1 fact. CLIPS> (watch facts) CLIPS> (modify 3 (age 2)) <== f-3 (person (name "Jack S. Public") (age 24) (eye-color blue) (hair-color black)) ==> f-4 (person (name "Jack S. Public") (age 25) (eye-color blue) (hair-color black) ) <Fact-4> CLIPS>

SEG 7450

29

T)e Deffacts Construct


It is often convenient to be able to automatically assert a set of facts instead of typing in the same assertions from the top level. :his is particularly true for facts that are -no#n to be true before running a program Ci.e., the initial -no#ledgeE. ?roups of facts that represent initial -no#ledge can be defined using the deffacts construct.
(deffacts people "Some people we know" (person (name "John Q. Public") (age 24) (eye-color blue) (hair-color black)) (person (name "Jack S. Public") (age 24) (eye-color blue) (hair-color black)) (person (name "Jane Q. Public") (age 36) (eye-color green) (hair-color red)))

SEG 7450

30

T)e Deffacts Construct


:he general format of a deffacts is: (deffacts <deffacts name> [<optional comment>] <facts>* ) :he facts in a deffacts statement are asserted using the CLIPS reset command. :he reset command removes all facts from the fact list and then asserts the facts from existing deffacts statement. (reset) 3ven if you have not defined any deffacts statements, a reset #ill assert the fact Cinitial!factE. :he fact identifier of the initial!fact is al#ays f!/.

SEG 7450

31

T)e Com onents of a Rule


<ules can be typed directly into CLIPS or loaded in from a file of rules. :he pseudocode for one of the possible rules in the industrial plant monitoring expert system is sho#n as follo#s:
IF the emergency is a fire THEN the response is to activate the sprinkler system

Lefore converting the pseudocode to a rule, the deftemplates for the types of facts referred to by the rule must be defined.
(deftemplate emergency (slot type)) #here the type field of the emergency fact #ould contain symbols such as fire, flood, and po#er outage. (deftemplate response (slot action)) #here the action field of the response fact indicates the response to be ta-en.

:he rule expressed in CLIPS is:


(defrule fire-emergency An example rule" (emergency (type fire)) => (assert (response (action activate-sprinkler-system))))
SEG 7450 32

T)e Com onents of a Rule


:he general format of a rule is: (defrule <rule name> [<comment>] <patterns>* ; Left-Hand Side (LHS) of the rule => <actions>* ); Right-Hand Side (RHS) of the rule :he entire rule must be surrounded by parentheses and each of the patterns and actions of the rule must be surrounded by parentheses. B rule may have multiple patterns and actions. :he parentheses surrounding patterns and actions must be properly balanced if they are nested. :he header of the rule consists of three parts. :he rule must start #ith the defrule -ey#ord, follo#ed by the name of the rule. Next comes an optional comment string.

SEG 7450

33

T)e Com onents of a Rule


3xample:
; Rule header (defrule fire-emergency An example rule" ; Patterns (emergency (type fire)) ; THEN arrow => ; Actions (assert (response (action activate-sprinklersystem))))

Bfter the rule header are 2ero or more conditional elements CC3sE. :he simplest type of C3 is a attern CE or simply attern& 3ach pattern consists of one or more constraints intended to match the fields of a deftemplate fact.
SEG 7450 34

T)e Com onents of a Rule


CLIPS attempts to match the patterns of rules against facts in the fact list. If all the patterns of a rule match facts, the rule is acti/ated and put on the agenda. the collection of activated rules. :he arro# is a symbol representing the beginning of the :;3N part of an I>!:;3N rule. :he part of the rule before the arro# is called the left!hand side CL;SE and the part after the arro# is called the right!hand side C<;SE. :he last part of a rule is the list of actions that #ill be executed #hen the rule fires. B program normally ceases execution #hen there are no rules on the agenda. 1hen there are multiple rules on the agenda, CLIPS automatically determines #hich is the appropriate rule to fire.

SEG 7450

35

T)e "genda and Execution


Execution -- run B CLIPS program can be made to run #ith the run command. :he syntax of the run command is: (run [<limit>])
#here the optional argument Glimit9 9is the maximum number of rules to be fired.

If Glimit9 is not included or Glimit9 is !(, rules #ill be fired until none are left on the agenda. Reset
Lecause rules reIuire facts to execute, the reset command is the -ey method for starting or restarting an expert system in CLIPS.

SEG 7450

36

0isplaying the Bgenda


:he list of rules on the agenda can be displayed #ith the agenda command. (agenda)

3xample:
CLIPS> (reset) CLIPS> (assert (emergency (type fire))) <Fact-1> CLIPS> (agenda) 0 fire-emergency: f-1 For a total of 1 activation. CLIPS> :he / indicates the salience of the rule on the agenda.

SEG 7450

37

<ules and <efraction


1ith the fire-emergency rule on the agenda, the run command #ill no# cause the rule to fire. :he fact Cresponse Caction activate!sprin-ler!system #ill be added to the fact list as the action of the rule: CLIPS> (run) CLIPS> (facts) f-0 (initial-fact) f-1 (emergency (type fire)) f-2 (response (action activatesprinkler-system)) For a total of 3 facts. CLIPS> <ules in CLIPS exhibit a property called refraction, #hich means they #ont fire more than once for a specific set of facts. Refres) :he refres) command can be used to ma-e the rule fire again. (refresh <rule-name>)
SEG 7450 38

1atching Bctivations, <ules, and Statistics


3xamples of #atching activations: CLIPS> (reset) CLIPS> (watch activations) CLIPS> (assert (emergency (type fire))) ==> Activation 0 fire-emergency: f-l <Fact-1> CLIPS> (agenda) 0 fire-emergency: f-l For a total of 1 activation. CLIPS> (retract 1) <== Activation 0 fire-emergency: f-1 CLIPS> (agenda) CLIPS>

SEG 7450

39

1atching Bctivations, <ules, and Statistics


<ules being #atched: CLIPS> (reset) CLIPS> (watch rules) CLIPS> (assert (emergency (type fire))) ==> Activation 0 fire-emergency: f-l <Fact-1> CLIPS> (run) FIRE 1 fire-emergency: f-l CLIPS> (agenda) CLIPS>

SEG 7450

40

1atching Bctivations, <ules, and Statistics


If statistics are #atched, informational messages #ill be printed at the completion of a run.
CLIPS> (unwatch all) CLIPS> (reset) CLIPS> (watch statistics) CLIPS> (assert (emergency (type fire))) <Fact-1> CLIPS> (run) 1 rules fired Run time is 0.02 seconds 50.0 rules per second 3 mean number of facts (3 maximum) 1 mean number of instances (1 maximum) 1 mean number of activations (1 maximum) CLIPS> (unwatch statistics) CLIPS>
SEG 7450 41

1atching Bctivations, <ules, and Statistics


CLIPS -eeps statistics on the number of facts, activations, and instances.
:he mean number of facts is the sum of the total number of facts in the fact list after each rule firing divided by the number of rules fired.

:he mean and maximum numbers of activations statistics indicate the average number of activations per rule firing and the largest number of activations on the agenda for anyone rule firing.

SEG 7450

42

Commands for Mani ulating Constructs


0isplaying the List of Members of a Specified Construct
(list-defrules) (list-deftemplates) (list-deffacts)

0isplaying the :ext <epresentation of a Specified Construct Member


(ppdefrule <defrule-name>) (ppdeftemplate <deftemplate-name>) (ppdeffacts <deffacts-name>)

0eleting a Specified Construct Member


(undefrule <defrule-name>) (undeftemplate <deftemplate-name>) (undeffacts <derfacts-name>)

Clearing Bll Constructs from the CLIPS 3nvironment


(clear)

SEG 7450

43

T)e PRI0T12T Command


Lesides asserting facts in the <;S of rules, the <;S can also be used to print out information using the printout command. (printout <logical-name> <print-items>*)
#here Glogical!name9 indicates the output destination of the printout command and Gprint!items9O are the 2ero or more items to be printed by this command.

3xample of rule using the printout command:


(defrule fire-emergency (emergency (type fire)) => (printout t Activate the sprinkler system" crlf) )

:he logical name t tells CLIPS to send the output to the standard output device of the computer, usually the terminal.

SEG 7450

44

2sing Multi le Rules


In addition to the fire-emergency rule, the expert system monitoring the industrial plant might include a rule for emergencies in #hich nooding has occurred. (defrule fire-emergency (emergency (type fire)) => (printout t "Activate the sprinkler system" crlf) ) (defrule flood-emergency (emergency (type flood)) => (printout t "Shut down electrical equipment" crlf) )

SEG 7450

45

2sing Multi le Rules


<ules #ith more than one pattern could be used to express these conditions.
(deftemplate extinguisher-system (slot type) (slot status)) (defrule class-A-fire-emergency (emergency (type class-A-fire)) (extinguisher-system (type water-sprinkler) (status off)) => (printout t "Activate water sprinkler" crlf)) (defrule class-B-fire-emergency (emergency (type class-B-fire)) (extinguisher-system (type carbon-dioxide) (status off)) => (printout t "Use carbon dioxide extinguisher" crlf) )
SEG 7450 46

2sing Multi le Rules


Bny number of patterns can be placed in a rule. :he important point to reali2e is that the rule is placed on the agenda only if all the patterns are satisfied by facts. :his type of restriction is called an and conditional element.

SEG 7450

47

T)e SET-BRE"3 Command


CLIPS has a debugging command called set- rea! that allo#s execution to be halted before any rule from a specified group of rules is fired. B rule that halts execution before being fired is called a rea!point. (set-break <rule-name>) 3xample #ith the follo#ing rules:
(defrule first => assert (fire second))) (defrule second (fire second) => assert (fire third)))

SEG 7450

48

T)e SET-BRE"3 Command


1ith set!breaCLIPS> (set-break second) CLIPS> (reset) CLIPS> (run) FILE 1 first: f-0 Breaking on the second CLIPS>

:he sho#!brea-s command can be used to list all brea-points. Its syntax is: (show-breaks) :he remove!brea- command can be used to remove brea-points. Its syntax (remove-break [<rule-name>])

SEG 7450

49

Loading and Saving Constructs


Loading Constructs from a File (load <file-name>)
#here Gfile!name9 is a string or symbol containing the name of the file to be loaded. 3.g. Cload fire.clpE

Sa/ing Constructs to a File


:he save command allo#s the set of constructs stored in CLIPS to be saved to a dis- file.

(save <file-name>)
3.g. Csave 5fire.clp8E

SEG 7450

50

Commenting Constructs
B comment in CILPS is any text that begins #ith a semicolon and ends #ith a carriage return. It is good to include comments describing the constructs, and giving information regarding the program.
;*************************** ;* Programmer: G. D. Riley * ;* Title: The Fire Program * ;* Date: 05/17/04 * ; Deftemplate (deftemplate emergency template #1 #1 (slot type)) ; What type of emergency (deftemplate response template #2 #2 (sloto type)) ; How to respond ; The purpose of this rule is to activate ; the sprinkler if there is a fire (defrule firefire-emergency An example rule rule ;IF (emergency (type fire)) => ; THEN ;Activate the sprinkler system (assert (response (action activateactivate-sprinkersprinker-system))))
SEG 7450 51

Você também pode gostar