Wednesday, December 16, 2009

EXPERT SYSTEM


Friday, November 27, 2009

Input Output (resume)

5.1 Outputting Terms
The main built-in predicate provided for outputting terms is write/1, which has
already been used many times in this book.
The write/1 predicate takes a single argument, which must be a valid Prolog
term. Evaluating the predicate causes the term to be written to the current output
stream, which by default is the user's screen. (The meaning of current output
70 Logic Programming With Prolog
stream will be explained in Sections 5.7 and 5.8. At present it can simply be taken
to mean the user's screen.)
The built-in predicate nl/0 has also been used many times previously in this
book. It takes no arguments. Evaluating a nl goal causes a new line to be output to
the current output stream.
Examples
?- write(26),nl.
26
yes
?- write('a string of characters'),nl.
a string of characters
yes
?- write([a,b,c,d,[x,y,z]]),nl.
[a,b,c,d,[x,y,z]]
yes
?- write(mypred(a,b,c)),nl.
mypred(a,b,c)
yes
?- write('Example of use of nl'),nl,nl,write('end of example'),nl.
Example of use of nl
end of example
yes
Note that atoms that have to be quoted on input (e.g. 'Paul', 'hello world') are not
quoted when output using write. If it is important to output the quotes, the
writeq/1 predicate can be used. It is identical to write/1 except that atoms that
need quotes for input are output between quotes (other atoms are not).
?- writeq('a string of characters'),nl.
'a string of characters'
yes
?-writeq(dog),nl.
dog
yes
?- writeq('dog'),nl.
dog
yes
Input and Output 71

The write/1 predicate takes a single argument, which must be a valid Prolog term. Evaluating the predicate causes the term to be written to the current output stream, which by default is the user's screen. The built-in predicate nl/0 has also been used many times previously in this book. It takes no arguments. Evaluating a nl goal causes a new line to be output to the current output stream.

If it is important to output the quotes, the writeq/1 predicate can be used.






5.2 Inputting Terms
The built-in predicate read/1 is provided to input terms. It takes a single argument,
which must be a variable.
Evaluating it causes the next term to be read from the current input stream,
which by default is the user's keyboard. (The meaning of current input stream will
be explained in Sections 5.7 and 5.9. At present it can simply be taken to mean the
user's keyboard.)
In the input stream, the term must be followed by a dot ('.') and at least one
white space character, such as space or newline. The dot and white space
characters are read in but are not considered part of the term.
Note that for input from the keyboard (only) a prompt character such as a colon
will usually be displayed to indicate that user input is required. It may be necessary
to press the 'return' key before Prolog will accept the input. Both of these do not
apply to input from files.
When a read goal is evaluated, the input term is unified with the argument
variable. If the variable is unbound (which is usually the case) it is bound to the
input value.
?- read(X).
: jim.
X = jim
?- read(X).
: 26.
X = 26
?- read(X).
: mypred(a,b,c).
X = mypred(a,b,c)
?- read(Z).
: [a,b,mypred(p,q,r),[z,y,x]].
Z = [a,b,mypred(p,q,r),[z,y,x]]
?- read(Y).
: 'a string of characters'.
Y = 'a string of characters'
If the argument variable is already bound (which for most users is far more
likely to occur by mistake than by design), the goal succeeds if and only if the
input term is identical to the previously bound value.
72 Logic Programming With Prolog
?- X=fred,read(X).
: jim.
no
?- X=fred,read(X).
: fred.
X = fred

The built-in predicate read/1 is provided to input terms. It takes a single argument, which must be a variable. Evaluating it causes the next term to be read from the current input stream, which by default is the user's keyboard. In the input stream, the term must be followed by a dot ('.') and at least one white space character, such as space or newline. The dot and white space characters are read in but are not considered part of the term.





5.3 Input and Output Using Characters
Although input and output of terms is straightforward, the use of quotes and full
stops can be cumbersome and is not always suitable. For example, it would be
tedious to define a predicate (using read) which would read a series of characters
from the keyboard and count the number of vowels. A much better approach for
problems of this kind is to input a character at a time. To do this it is first necessary
to know about the ASCII value of a character.
All printing characters and many non-printing characters (such as space and
tab) have a corresponding ASCII (American Standard Code for Information
Interchange) value, which is an integer from 0 to 255.
The table below gives the numerical ASCII values corresponding to the main
printable characters and some others.
9 tab
10
end of
record
32 space
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
48-57 0 to 9
58 :
59 ;
60 < 61 = 62 >
63 ?
64 @
65-
90
A to Z
91 [
92 \
93 ]
94 ^
95 _
96 `
97-
122
a to z
123 {
124 |
125 }
126 ~
Characters whose ASCII value is less than or equal to 32 are known as white
space characters.

Although input and output of terms is straightforward, the use of quotes and full stops can be cumbersome and is not always suitable. For example, it would be tedious to define a predicate (using read) which would read a series of characters from the keyboard and count the number of vowels. A much better approach for problems of this kind is to input a character at a time. To do this it is first necessary to know about the ASCII value of a character.
All printing characters and many non-printing characters (such as space and tab) have a corresponding ASCII (American Standard Code for Information Interchange) value, which is an integer from 0 to 255. The table below gives the numerical ASCII values corresponding to the main printable characters and some others.



5.4 Outputting Characters
Characters are output using the built-in predicate put/1. The predicate takes a
single argument, which must be a number from 0 to 255 or an expression that
evaluates to an integer in that range.
Evaluating a put goal causes a single character to be output to the current
output stream. This is the character corresponding to the numerical value (ASCII
value) of its argument, for example
?- put(97),nl.
a
yes
?- put(122),nl.
z
yes
?- put(64),nl.
@
Yes

Characters are output using the built-in predicate put/1. The predicate takes a single argument, which must be a number from 0 to 255 or an expression that evaluates to an integer in that range.
Evaluating a put goal causes a single character to be output to the current output stream. This is the character corresponding to the numerical value (ASCII value) of its argument.




5.5 Inputting Characters
Two built-in predicates are provided to input a single character: get0/1 and get/1.
The get0 predicate takes a single argument, which must be a variable. Evaluating a
get0 goal causes a character to be read from the current input stream. The variable
is then unified with the ASCII value of this character.
Note that for input from the keyboard (only) a prompt character such as a colon
will usually be displayed to indicate that user input is required. It may be necessary
to press the 'return' key before Prolog will accept the input. Both of these also
apply to the get predicate described below but do not apply to input from files.
Assuming the argument variable is unbound (which will usually be the case), it
is bound to the ASCII value of the input character.
?- get0(N).
: a
N = 97
?- get0(N).
: Z
N = 90
74 Logic Programming With Prolog
?- get0(M)
: )
M = 41
If the argument variable is already bound, the goal succeeds if and only if it has
a numerical value that is equal to the ASCII value of the input character.
?- get0(X).
: a
X = 97
?- M is 41,get0(M).
: )
M = 41
?- M=dog,get0(M).
: )
no
?- M=41.001,get0(M).
: )
no
The get predicate takes a single argument, which must be a variable. Evaluating
a get goal causes the next non-white-space character (i.e. character with an ASCII
value less than or equal to 32) to be read from the current input stream. The
variable is then unified with the ASCII value of this character in the same way as
for get0.
?- get(X).
: Z
X = 90
?- get(M).
: Z
M = 90
Two built-in predicates are provided to input a single character: get0/1 and get/1. The get0 predicate takes a single argument, which must be a variable. Evaluating a get0 goal causes a character to be read from the current input stream. The variable is then unified with the ASCII value of this character.
Assuming the argument variable is unbound (which will usually be the case), it
is bound to the ASCII value of the input character.






5.6 Using Characters: Examples
The first example shows how to read in a series of characters from the keyboard
finishing with * and to output their corresponding ASCII values one per line (for
all characters excluding *).
The predicate readin is defined recursively. It causes a single character to be
input and variable X to be bound to its (numerical) ASCII value. The action taken
(the process(X) goal) depends on whether or not X has the value 42 signifying a *
Input and Output 75
character. If it has, the evaluation of the goal stops. If not, the value of X is output,
followed by a new line, followed by a further call to readin. This process goes on
indefinitely until a * character is read. (In the example below, the ASCII values of
characters P, r, o etc. are correctly shown to be 80, 114, 111 etc.)
readin:-get0(X),process(X).
process(42).
process(X):-X=\=42,write(X),nl,readin.

?- readin.
: Prolog Example*
80
114
111
108
111
103
32
69
120
97
109
112
108
101
yes
The next example is an extended version of the one above. This time the ASCII
values of the input characters are not output, but the number of characters
(excluding the *) is output. The count predicate is defined with two arguments
which can be read as 'the number of characters counted so far' and 'the total number
of characters before the *'.
go(Total):-count(0,Total).
count(Oldcount,Result):-
get0(X),process(X,Oldcount,Result).
process(42,Oldcount,Oldcount).
process(X,Oldcount,Result):-
X=\=42,New is Oldcount+1,count(New,Result).
?- go(T).
: The time has come the walrus said*
T = 33
76 Logic Programming With Prolog
?- go(T).
: *
T = 0
The final example is a recursive program, based on the previous two, which
shows how to read in a series of characters ending with * and count the number of
vowels. Characters are read in one by one until a character with ASCII value 42
(signifying *) is encountered.
Here the two arguments of the count predicate can be interpreted as 'the
number of vowels so far' and 'the total number of vowels'. The three arguments of
the process predicate can be read as 'the ASCII value of an input character', 'the
number of vowels up to but not including that character' and 'the total number of
vowels', respectively.
The first two arguments of the processChar predicate can be interpreted in the
same way as for process, but the third argument is 'the number of vowels up to and
including the character (first argument)'.
Predicate vowel tests for one of the 10 possible vowels (five upper case and
five lower case), using their ASCII values.
go(Vowels):-count(0,Vowels).
count(Oldvowels,Totvowels):-
get0(X),process(X,Oldvowels,Totvowels).
process(42,Oldvowels,Oldvowels).
process(X,Oldvowels,Totalvowels):-
X=\=42,processChar(X,Oldvowels,New),
count(New,Totalvowels).
processChar(X,Oldvowels,New):-vowel(X),
New is Oldvowels+1.
processChar(X,Oldvowels,Oldvowels).
vowel(65). /* A */
vowel(69). /* E */
vowel(73). /* I */
vowel(79). /* O */
vowel(85). /* U */
vowel(97). /* a */
vowel(101). /* e */
vowel(105). /* i */
Input and Output 77
vowel(111). /* o */
vowel(117). /* u */
?- go(Vowels).
: In the beginning was the word*
Vowels = 8
?- go(Vowels).
: pqrst*
Vowels = 0

The first example shows how to read in a series of characters from the keyboard finishing with * and to output their corresponding ASCII values one per line (for all characters excluding *). The predicate readin is defined recursively. It causes a single character to be input and variable X to be bound to its (numerical) ASCII value. The action taken (the process(X) goal) depends on whether or not X has the value 42 signifying a *character. If it has, the evaluation of the goal stops. If not, the value of X is output, followed by a new line, followed by a further call to readin. This process goes on indefinitely until a * character is read. (In the example below, the ASCII values of characters P, r, o etc. are correctly shown to be 80, 114, 111 etc.)

The final example is a recursive program, based on the previous two, which shows how to read in a series of characters ending with * and count the number of vowels. Characters are read in one by one until a character with ASCII value 42 (signifying *) is encountered.
Here the two arguments of the count predicate can be interpreted as 'the number of vowels so far' and 'the total number of vowels'. The three arguments of the process predicate can be read as 'the ASCII value of an input character', 'the number of vowels up to but not including that character' and 'the total number of vowels', respectively.
The first two arguments of the processChar predicate can be interpreted in the same way as for process, but the third argument is 'the number of vowels up to and including the character (first argument)'.
Predicate vowel tests for one of the 10 possible vowels (five upper case and five lower case), using their ASCII values.




5.7 Input and Output Using Files
Prolog takes all input from the current input stream and writes all output to the
current output stream. By default both of these are the stream named user,
denoting the user's terminal, i.e. keyboard for input and screen for output.
The same facilities available for input and output from and to the user's
terminal either term by term or character by character are also available for input
and output from and to files (e.g. files on a hard disk or a CD-ROM).
The user may open and close input and output streams associated with any
number of named files but there can only be one current input stream and one
current output stream at any time. Note that no file can be open for both input and
output at the same time (except user) and that the user input and output streams
cannot be closed.

Prolog takes all input from the current input stream and writes all output to the current output stream. By default both of these are the stream named user, denoting the user's terminal, i.e. keyboard for input and screen for output.
The same facilities available for input and output from and to the user's terminal either term by term or character by character are also available for input and output from and to files (e.g. files on a hard disk or a CD-ROM).
The user may open and close input and output streams associated with any number of named files but there can only be one current input stream and one current output stream at any time. Note that no file can be open for both input and output at the same time (except user) and that the user input and output streams cannot be closed.





5.8 File Output: Changing the Current Output Stream
The current output stream can be changed using the tell/1 predicate. This takes a
single argument, which is an atom or variable representing a file name, e.g.
tell('outfile.txt').
Evaluating a tell goal causes the named file to become the current output
stream. If the file is not already open, a file with the specified name is first created
(any existing file with the same name is deleted).
Note that the file corresponding to the previous current output stream remains
open when a new current output stream is selected. Only the current output stream
can be closed (using the told predicate described below).
The default current output stream is user, i.e. the user's terminal. This value can
be restored either by using the told predicate or by tell(user).
The built-in predicate told/0 takes no arguments. Evaluating a told goal causes
the current output file to be closed and the current output stream to be reset to user,
i.e. the user's terminal.
The built-in predicate telling/1 takes one argument, which must be a variable
and will normally be unbound. Evaluating a telling goal causes the variable to be
bound to the name of the current output stream.
78 Logic Programming With Prolog
Output to a File
Although the above definition of tell states that 'any existing file with the same
name is deleted', there is another possibility, which is important for some
applications, namely that the file is not deleted and any output is placed after the
end of the existing contents of the file. Both the 'overwrite' and the 'append' options
are likely to be available in any practical implementation of Prolog but may
involve using a different predicate (e.g. open) instead of or as well as tell. See the
documentation of your version of Prolog for details.

The current output stream can be changed using the tell/1 predicate. This takes a single argument, which is an atom or variable representing a file name, e.g. tell('outfile.txt').
Evaluating a tell goal causes the named file to become the current output stream. If the file is not already open, a file with the specified name is first created (any existing file with the same name is deleted).
Note that the file corresponding to the previous current output stream remains open when a new current output stream is selected. Only the current output stream can be closed (using the told predicate described below).
The default current output stream is user, i.e. the user's terminal. This value can be restored either by using the told predicate or by tell(user).
The built-in predicate told/0 takes no arguments. Evaluating a told goal causes the current output file to be closed and the current output stream to be reset to user, i.e. the user's terminal.
The built-in predicate telling/1 takes one argument, which must be a variable and will normally be unbound. Evaluating a telling goal causes the variable to be bound to the name of the current output stream.




5.9 File Input: Changing the Current Input Stream
The current input stream can be changed using the see/1 predicate. This takes a
single argument, which is an atom or variable representing a file name, e.g.
see('myfile.txt').
Evaluating a see goal causes the named file to become the current input stream.
If the file is not already open it is first opened (for read access only). If it is not
possible to open a file with the given name, an error will be generated.
Note that the file corresponding to the previous current input stream remains
open when a new current input stream is selected. Only the current input stream
can be closed (using the seen predicate described below).
The default current input stream is user, i.e. the user's terminal. This value can
be restored either by using the seen predicate or by see(user).
The built-in predicate seen/0 takes no arguments. Evaluating a see goal causes
the current input file to be closed and the current input stream to be reset to user,
i.e. the user's terminal.
The built-in predicate seeing/1 takes one argument, which must be a variable
and will normally be unbound. Evaluating a seeing goal causes the variable to be
bound to the name of the current input stream.
5.9.1 Reading from Files: End of File
If the end of file is encountered when evaluating the goal read(X), variable X will
be bound to the atom end_of_file.
If the end of file is encountered while evaluating the goal get(X) or get0(X),
variable X will be bound to a 'special' numerical value. As ASCII values must be in
the range 0 to 255 inclusive, this will typically be -1, but may vary from one
implementation of Prolog to another.






5.9.2 Reading from Files: End of Record
Depending on the version of Prolog used, there may be an incompatibility for
character input between reading the end of a record (i.e. the character(s) that
signify the end of a line) from the user's terminal and from a file.
Typically the end of a line of input at the user's terminal will be indicated by
the character with ASCII value 13. The end of a record in a file will generally be
indicated by two ASCII values: 13 followed by 10.
The following program shows how to read in a series of characters from the
keyboard and print them out, one per line.
readline:-get0(X),process(X).
process(13).
process(X):-X=\=13,put(X),nl,readline.
Note the use of put rather than write and that the test for ASCII value 13
avoids the need for a character such as * to indicate 'end of input'.
?- readline.
: Prolog test
Pr
ol
og
t
est
yes

The current input stream can be changed using the see/1 predicate. This takes a single argument, which is an atom or variable representing a file name, e.g. see('myfile.txt').
Evaluating a see goal causes the named file to become the current input stream. If the file is not already open it is first opened (for read access only). If it is not possible to open a file with the given name, an error will be generated. Note that the file corresponding to the previous current input stream remains open when a new current input stream is selected. Only the current input stream can be closed (using the seen predicate described below).
The default current input stream is user, i.e. the user's terminal. This value can be restored either by using the seen predicate or by see(user).
The built-in predicate seen/0 takes no arguments. Evaluating a see goal causes the current input file to be closed and the current input stream to be reset to user, i.e. the user's terminal.
The built-in predicate seeing/1 takes one argument, which must be a variable and will normally be unbound. Evaluating a seeing goal causes the variable to be bound to the name of the current input stream .

Input Output (resume)

5.1 Outputting Terms
The main built-in predicate provided for outputting terms is write/1, which has
already been used many times in this book.
The write/1 predicate takes a single argument, which must be a valid Prolog
term. Evaluating the predicate causes the term to be written to the current output
stream, which by default is the user's screen. (The meaning of current output
70 Logic Programming With Prolog
stream will be explained in Sections 5.7 and 5.8. At present it can simply be taken
to mean the user's screen.)
The built-in predicate nl/0 has also been used many times previously in this
book. It takes no arguments. Evaluating a nl goal causes a new line to be output to
the current output stream.
Examples
?- write(26),nl.
26
yes
?- write('a string of characters'),nl.
a string of characters
yes
?- write([a,b,c,d,[x,y,z]]),nl.
[a,b,c,d,[x,y,z]]
yes
?- write(mypred(a,b,c)),nl.
mypred(a,b,c)
yes
?- write('Example of use of nl'),nl,nl,write('end of example'),nl.
Example of use of nl
end of example
yes
Note that atoms that have to be quoted on input (e.g. 'Paul', 'hello world') are not
quoted when output using write. If it is important to output the quotes, the
writeq/1 predicate can be used. It is identical to write/1 except that atoms that
need quotes for input are output between quotes (other atoms are not).
?- writeq('a string of characters'),nl.
'a string of characters'
yes
?-writeq(dog),nl.
dog
yes
?- writeq('dog'),nl.
dog
yes
Input and Output 71

The write/1 predicate takes a single argument, which must be a valid Prolog term. Evaluating the predicate causes the term to be written to the current output stream, which by default is the user's screen. The built-in predicate nl/0 has also been used many times previously in this book. It takes no arguments. Evaluating a nl goal causes a new line to be output to the current output stream.

If it is important to output the quotes, the writeq/1 predicate can be used.






5.2 Inputting Terms
The built-in predicate read/1 is provided to input terms. It takes a single argument,
which must be a variable.
Evaluating it causes the next term to be read from the current input stream,
which by default is the user's keyboard. (The meaning of current input stream will
be explained in Sections 5.7 and 5.9. At present it can simply be taken to mean the
user's keyboard.)
In the input stream, the term must be followed by a dot ('.') and at least one
white space character, such as space or newline. The dot and white space
characters are read in but are not considered part of the term.
Note that for input from the keyboard (only) a prompt character such as a colon
will usually be displayed to indicate that user input is required. It may be necessary
to press the 'return' key before Prolog will accept the input. Both of these do not
apply to input from files.
When a read goal is evaluated, the input term is unified with the argument
variable. If the variable is unbound (which is usually the case) it is bound to the
input value.
?- read(X).
: jim.
X = jim
?- read(X).
: 26.
X = 26
?- read(X).
: mypred(a,b,c).
X = mypred(a,b,c)
?- read(Z).
: [a,b,mypred(p,q,r),[z,y,x]].
Z = [a,b,mypred(p,q,r),[z,y,x]]
?- read(Y).
: 'a string of characters'.
Y = 'a string of characters'
If the argument variable is already bound (which for most users is far more
likely to occur by mistake than by design), the goal succeeds if and only if the
input term is identical to the previously bound value.
72 Logic Programming With Prolog
?- X=fred,read(X).
: jim.
no
?- X=fred,read(X).
: fred.
X = fred

The built-in predicate read/1 is provided to input terms. It takes a single argument, which must be a variable. Evaluating it causes the next term to be read from the current input stream, which by default is the user's keyboard. In the input stream, the term must be followed by a dot ('.') and at least one white space character, such as space or newline. The dot and white space characters are read in but are not considered part of the term.





5.3 Input and Output Using Characters
Although input and output of terms is straightforward, the use of quotes and full
stops can be cumbersome and is not always suitable. For example, it would be
tedious to define a predicate (using read) which would read a series of characters
from the keyboard and count the number of vowels. A much better approach for
problems of this kind is to input a character at a time. To do this it is first necessary
to know about the ASCII value of a character.
All printing characters and many non-printing characters (such as space and
tab) have a corresponding ASCII (American Standard Code for Information
Interchange) value, which is an integer from 0 to 255.
The table below gives the numerical ASCII values corresponding to the main
printable characters and some others.
9 tab
10
end of
record
32 space
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
48-57 0 to 9
58 :
59 ;
60 < 61 = 62 >
63 ?
64 @
65-
90
A to Z
91 [
92 \
93 ]
94 ^
95 _
96 `
97-
122
a to z
123 {
124 |
125 }
126 ~
Characters whose ASCII value is less than or equal to 32 are known as white
space characters.

Although input and output of terms is straightforward, the use of quotes and full stops can be cumbersome and is not always suitable. For example, it would be tedious to define a predicate (using read) which would read a series of characters from the keyboard and count the number of vowels. A much better approach for problems of this kind is to input a character at a time. To do this it is first necessary to know about the ASCII value of a character.
All printing characters and many non-printing characters (such as space and tab) have a corresponding ASCII (American Standard Code for Information Interchange) value, which is an integer from 0 to 255. The table below gives the numerical ASCII values corresponding to the main printable characters and some others.



5.4 Outputting Characters
Characters are output using the built-in predicate put/1. The predicate takes a
single argument, which must be a number from 0 to 255 or an expression that
evaluates to an integer in that range.
Evaluating a put goal causes a single character to be output to the current
output stream. This is the character corresponding to the numerical value (ASCII
value) of its argument, for example
?- put(97),nl.
a
yes
?- put(122),nl.
z
yes
?- put(64),nl.
@
Yes

Characters are output using the built-in predicate put/1. The predicate takes a single argument, which must be a number from 0 to 255 or an expression that evaluates to an integer in that range.
Evaluating a put goal causes a single character to be output to the current output stream. This is the character corresponding to the numerical value (ASCII value) of its argument.




5.5 Inputting Characters
Two built-in predicates are provided to input a single character: get0/1 and get/1.
The get0 predicate takes a single argument, which must be a variable. Evaluating a
get0 goal causes a character to be read from the current input stream. The variable
is then unified with the ASCII value of this character.
Note that for input from the keyboard (only) a prompt character such as a colon
will usually be displayed to indicate that user input is required. It may be necessary
to press the 'return' key before Prolog will accept the input. Both of these also
apply to the get predicate described below but do not apply to input from files.
Assuming the argument variable is unbound (which will usually be the case), it
is bound to the ASCII value of the input character.
?- get0(N).
: a
N = 97
?- get0(N).
: Z
N = 90
74 Logic Programming With Prolog
?- get0(M)
: )
M = 41
If the argument variable is already bound, the goal succeeds if and only if it has
a numerical value that is equal to the ASCII value of the input character.
?- get0(X).
: a
X = 97
?- M is 41,get0(M).
: )
M = 41
?- M=dog,get0(M).
: )
no
?- M=41.001,get0(M).
: )
no
The get predicate takes a single argument, which must be a variable. Evaluating
a get goal causes the next non-white-space character (i.e. character with an ASCII
value less than or equal to 32) to be read from the current input stream. The
variable is then unified with the ASCII value of this character in the same way as
for get0.
?- get(X).
: Z
X = 90
?- get(M).
: Z
M = 90
Two built-in predicates are provided to input a single character: get0/1 and get/1. The get0 predicate takes a single argument, which must be a variable. Evaluating a get0 goal causes a character to be read from the current input stream. The variable is then unified with the ASCII value of this character.
Assuming the argument variable is unbound (which will usually be the case), it
is bound to the ASCII value of the input character.






5.6 Using Characters: Examples
The first example shows how to read in a series of characters from the keyboard
finishing with * and to output their corresponding ASCII values one per line (for
all characters excluding *).
The predicate readin is defined recursively. It causes a single character to be
input and variable X to be bound to its (numerical) ASCII value. The action taken
(the process(X) goal) depends on whether or not X has the value 42 signifying a *
Input and Output 75
character. If it has, the evaluation of the goal stops. If not, the value of X is output,
followed by a new line, followed by a further call to readin. This process goes on
indefinitely until a * character is read. (In the example below, the ASCII values of
characters P, r, o etc. are correctly shown to be 80, 114, 111 etc.)
readin:-get0(X),process(X).
process(42).
process(X):-X=\=42,write(X),nl,readin.

?- readin.
: Prolog Example*
80
114
111
108
111
103
32
69
120
97
109
112
108
101
yes
The next example is an extended version of the one above. This time the ASCII
values of the input characters are not output, but the number of characters
(excluding the *) is output. The count predicate is defined with two arguments
which can be read as 'the number of characters counted so far' and 'the total number
of characters before the *'.
go(Total):-count(0,Total).
count(Oldcount,Result):-
get0(X),process(X,Oldcount,Result).
process(42,Oldcount,Oldcount).
process(X,Oldcount,Result):-
X=\=42,New is Oldcount+1,count(New,Result).
?- go(T).
: The time has come the walrus said*
T = 33
76 Logic Programming With Prolog
?- go(T).
: *
T = 0
The final example is a recursive program, based on the previous two, which
shows how to read in a series of characters ending with * and count the number of
vowels. Characters are read in one by one until a character with ASCII value 42
(signifying *) is encountered.
Here the two arguments of the count predicate can be interpreted as 'the
number of vowels so far' and 'the total number of vowels'. The three arguments of
the process predicate can be read as 'the ASCII value of an input character', 'the
number of vowels up to but not including that character' and 'the total number of
vowels', respectively.
The first two arguments of the processChar predicate can be interpreted in the
same way as for process, but the third argument is 'the number of vowels up to and
including the character (first argument)'.
Predicate vowel tests for one of the 10 possible vowels (five upper case and
five lower case), using their ASCII values.
go(Vowels):-count(0,Vowels).
count(Oldvowels,Totvowels):-
get0(X),process(X,Oldvowels,Totvowels).
process(42,Oldvowels,Oldvowels).
process(X,Oldvowels,Totalvowels):-
X=\=42,processChar(X,Oldvowels,New),
count(New,Totalvowels).
processChar(X,Oldvowels,New):-vowel(X),
New is Oldvowels+1.
processChar(X,Oldvowels,Oldvowels).
vowel(65). /* A */
vowel(69). /* E */
vowel(73). /* I */
vowel(79). /* O */
vowel(85). /* U */
vowel(97). /* a */
vowel(101). /* e */
vowel(105). /* i */
Input and Output 77
vowel(111). /* o */
vowel(117). /* u */
?- go(Vowels).
: In the beginning was the word*
Vowels = 8
?- go(Vowels).
: pqrst*
Vowels = 0

The first example shows how to read in a series of characters from the keyboard finishing with * and to output their corresponding ASCII values one per line (for all characters excluding *). The predicate readin is defined recursively. It causes a single character to be input and variable X to be bound to its (numerical) ASCII value. The action taken (the process(X) goal) depends on whether or not X has the value 42 signifying a *character. If it has, the evaluation of the goal stops. If not, the value of X is output, followed by a new line, followed by a further call to readin. This process goes on indefinitely until a * character is read. (In the example below, the ASCII values of characters P, r, o etc. are correctly shown to be 80, 114, 111 etc.)

The final example is a recursive program, based on the previous two, which shows how to read in a series of characters ending with * and count the number of vowels. Characters are read in one by one until a character with ASCII value 42 (signifying *) is encountered.
Here the two arguments of the count predicate can be interpreted as 'the number of vowels so far' and 'the total number of vowels'. The three arguments of the process predicate can be read as 'the ASCII value of an input character', 'the number of vowels up to but not including that character' and 'the total number of vowels', respectively.
The first two arguments of the processChar predicate can be interpreted in the same way as for process, but the third argument is 'the number of vowels up to and including the character (first argument)'.
Predicate vowel tests for one of the 10 possible vowels (five upper case and five lower case), using their ASCII values.




5.7 Input and Output Using Files
Prolog takes all input from the current input stream and writes all output to the
current output stream. By default both of these are the stream named user,
denoting the user's terminal, i.e. keyboard for input and screen for output.
The same facilities available for input and output from and to the user's
terminal either term by term or character by character are also available for input
and output from and to files (e.g. files on a hard disk or a CD-ROM).
The user may open and close input and output streams associated with any
number of named files but there can only be one current input stream and one
current output stream at any time. Note that no file can be open for both input and
output at the same time (except user) and that the user input and output streams
cannot be closed.

Prolog takes all input from the current input stream and writes all output to the current output stream. By default both of these are the stream named user, denoting the user's terminal, i.e. keyboard for input and screen for output.
The same facilities available for input and output from and to the user's terminal either term by term or character by character are also available for input and output from and to files (e.g. files on a hard disk or a CD-ROM).
The user may open and close input and output streams associated with any number of named files but there can only be one current input stream and one current output stream at any time. Note that no file can be open for both input and output at the same time (except user) and that the user input and output streams cannot be closed.





5.8 File Output: Changing the Current Output Stream
The current output stream can be changed using the tell/1 predicate. This takes a
single argument, which is an atom or variable representing a file name, e.g.
tell('outfile.txt').
Evaluating a tell goal causes the named file to become the current output
stream. If the file is not already open, a file with the specified name is first created
(any existing file with the same name is deleted).
Note that the file corresponding to the previous current output stream remains
open when a new current output stream is selected. Only the current output stream
can be closed (using the told predicate described below).
The default current output stream is user, i.e. the user's terminal. This value can
be restored either by using the told predicate or by tell(user).
The built-in predicate told/0 takes no arguments. Evaluating a told goal causes
the current output file to be closed and the current output stream to be reset to user,
i.e. the user's terminal.
The built-in predicate telling/1 takes one argument, which must be a variable
and will normally be unbound. Evaluating a telling goal causes the variable to be
bound to the name of the current output stream.
78 Logic Programming With Prolog
Output to a File
Although the above definition of tell states that 'any existing file with the same
name is deleted', there is another possibility, which is important for some
applications, namely that the file is not deleted and any output is placed after the
end of the existing contents of the file. Both the 'overwrite' and the 'append' options
are likely to be available in any practical implementation of Prolog but may
involve using a different predicate (e.g. open) instead of or as well as tell. See the
documentation of your version of Prolog for details.

The current output stream can be changed using the tell/1 predicate. This takes a single argument, which is an atom or variable representing a file name, e.g. tell('outfile.txt').
Evaluating a tell goal causes the named file to become the current output stream. If the file is not already open, a file with the specified name is first created (any existing file with the same name is deleted).
Note that the file corresponding to the previous current output stream remains open when a new current output stream is selected. Only the current output stream can be closed (using the told predicate described below).
The default current output stream is user, i.e. the user's terminal. This value can be restored either by using the told predicate or by tell(user).
The built-in predicate told/0 takes no arguments. Evaluating a told goal causes the current output file to be closed and the current output stream to be reset to user, i.e. the user's terminal.
The built-in predicate telling/1 takes one argument, which must be a variable and will normally be unbound. Evaluating a telling goal causes the variable to be bound to the name of the current output stream.




5.9 File Input: Changing the Current Input Stream
The current input stream can be changed using the see/1 predicate. This takes a
single argument, which is an atom or variable representing a file name, e.g.
see('myfile.txt').
Evaluating a see goal causes the named file to become the current input stream.
If the file is not already open it is first opened (for read access only). If it is not
possible to open a file with the given name, an error will be generated.
Note that the file corresponding to the previous current input stream remains
open when a new current input stream is selected. Only the current input stream
can be closed (using the seen predicate described below).
The default current input stream is user, i.e. the user's terminal. This value can
be restored either by using the seen predicate or by see(user).
The built-in predicate seen/0 takes no arguments. Evaluating a see goal causes
the current input file to be closed and the current input stream to be reset to user,
i.e. the user's terminal.
The built-in predicate seeing/1 takes one argument, which must be a variable
and will normally be unbound. Evaluating a seeing goal causes the variable to be
bound to the name of the current input stream.
5.9.1 Reading from Files: End of File
If the end of file is encountered when evaluating the goal read(X), variable X will
be bound to the atom end_of_file.
If the end of file is encountered while evaluating the goal get(X) or get0(X),
variable X will be bound to a 'special' numerical value. As ASCII values must be in
the range 0 to 255 inclusive, this will typically be -1, but may vary from one
implementation of Prolog to another.






5.9.2 Reading from Files: End of Record
Depending on the version of Prolog used, there may be an incompatibility for
character input between reading the end of a record (i.e. the character(s) that
signify the end of a line) from the user's terminal and from a file.
Typically the end of a line of input at the user's terminal will be indicated by
the character with ASCII value 13. The end of a record in a file will generally be
indicated by two ASCII values: 13 followed by 10.
The following program shows how to read in a series of characters from the
keyboard and print them out, one per line.
readline:-get0(X),process(X).
process(13).
process(X):-X=\=13,put(X),nl,readline.
Note the use of put rather than write and that the test for ASCII value 13
avoids the need for a character such as * to indicate 'end of input'.
?- readline.
: Prolog test
Pr
ol
og
t
est
yes

The current input stream can be changed using the see/1 predicate. This takes a single argument, which is an atom or variable representing a file name, e.g. see('myfile.txt').
Evaluating a see goal causes the named file to become the current input stream. If the file is not already open it is first opened (for read access only). If it is not possible to open a file with the given name, an error will be generated. Note that the file corresponding to the previous current input stream remains open when a new current input stream is selected. Only the current input stream can be closed (using the seen predicate described below).
The default current input stream is user, i.e. the user's terminal. This value can be restored either by using the seen predicate or by see(user).
The built-in predicate seen/0 takes no arguments. Evaluating a see goal causes the current input file to be closed and the current input stream to be reset to user, i.e. the user's terminal.
The built-in predicate seeing/1 takes one argument, which must be a variable and will normally be unbound. Evaluating a seeing goal causes the variable to be bound to the name of the current input stream .

GAYA KEPEMIMPINAN


Manusia memiliki karakter yang berbeda-beda dan umumnya karakter seseorang berhubungan dengan gaya kepimimpinannya,namun kebanyakan orang tidak menyadari hal itu.Banyak kasus seperti pegawai dimarahin oleh atasan,anggota dimarahin oleh ketua,menurut kami itu semua karena anggota atau pegawai terssebut kurang memahami gaya kepimipinan atasan atau ketunya,oleh karena itu kami disini membantu untuk mengenali gaya kepemimpinan seseorang melalui karakter  yang dimiliki.
Benefit :
1.       Kita dapat mengenali gaya kepimipinan seseorang dari karakter yang mereka miliki.
2.       Kita dapat mengatasi hambatan-hambatan yang timbul dari sifat leader,karena kita sudah mengetahui gaya kepemimpinannya
3.       Kita dapat mencocokkan tentang attitude yang nantinya harus kita lakukan kepada seorang leader


Gaya kepemimpinan, pada dasarnya mengandung pengertian sebagai suatu perwujudan tingkah laku dari seorang pemimpin, yang menyangkut kemampuannya dalam memimpin. Perwujudan tersebut biasanya membentuk suatu pola atau bentuk tertentu
Tujuan: untuk mencocokkan karakteristik seseorang dengan gaya kepemiminannya karena karakter berhubungan erat dengan tipekal gaya kepemimpinan seseorang.
Tipekal kepemimpinan:

1.    Tipe Otokratis
2.    Tipe Militeristis
3.    Tipe Paternalistis
4.    Tipe karismatik
5.    Tipe demokratis

Penjelasan:
1.    Tiepe Otokratis
a.    Menganggap organisasi sebagai pemilik pribadi;
b.    Mengidentikkan tujuan pribadi dengan tujuan organisasi;
c.    Menganggap bawahan sebagai alat semata-mata;
d.    Tidak mau menerima kritik, saran dan pendapat;
e.    Terlalu tergantung kepada kekuasaan formalnya;
f.    Dalam tindakan pengge-rakkannya sering memperguna-kan pendekatan yang mengandung unsur paksaan dan bersifat menghukum.

2.    Tipe Militeristis
a.    Dalam menggerakan bawahan sistem perintah yang lebih sering dipergunakan;
b.    Dalam menggerakkan bawahan senang bergantung kepada pangkat dan jabatannya;
c.    Senang pada formalitas yang berlebih-lebihan;
d.    Menuntut disiplin yang tinggi dan kaku dari bawahan;
e.    Sukar menerima kritikan dari bawahannya; Menggemari upacara-upacara untuk berbagai keadaan.

3.    Tipe Paternalistis
A. menganggap bawahannya sebagai manusia yang tidak dewasa;
b. bersikap terlalu melindungi (overly protective);
c. jarang memberikan kesempatan kepada bawahannya untuk mengambil keputusan;
d. jarang memberikan kesempatan kepada bawahannya untuk mengambil inisiatif;
e. jarang memberikan kesempatan kepada bawahannya untuk mengembangkan daya    kreasi dan fantasinya; dan sering bersikap maha tahu.
4. Tipe Karismatik

a. Dapat mempengaruhi seseorang
b. Mau memberikan kesempatan pada bawahannya untuk mengambil keputusan
c. Mau menerima kritik dan saran dari orang lain
d. Dalam tindakan penggerakannya sering menggunakan pendekatan yang bersifat social
e. disenangi banyak orang
f. memiliki pengikut

5. Tipe Demokratis
a. dalam proses penggerakan bawahan selalu bertitik tolak dari pendapat bahwa manusia itu adalah makhluk yang termulia di dunia;
b. selalu berusaha mensinkronisasikan kepentingan dan tujuan organisasi dengan kepentingan dan tujuan pribadi dari pada bawahannya;
c. senang menerima saran, pendapat, dan bahkan kritik dari bawahannya;
d. selalu berusaha mengutamakan kerjasama dan teamwork dalam usaha mencapai tujuan;
e. ikhlas memberikan kebebasan yang seluas-luasnya kepada bawahannya untuk berbuat kesalahan yang kemudian diperbaiki agar bawahan itu tidak lagi berbuat kesalahan yang sama, tetapi lebih berani untuk berbuat kesalahan yang lain;
f. selalu berusaha untuk menjadikan bawahannya lebih sukses daripadanya;
g. berusaha mengembangkan kapasitas diri pribadinya sebagai pemimpin.

Thursday, November 12, 2009

FINAL PROJECT 4

NOMOR 1 =

Soal =


























Jawab :

Contoh :
likes(john,X). Gunakan sisipan operator — > john likes X dog(fred). Gunakan awalan operator –> isa_dog(fred). Gunakan awalan operator –> fred is_a_dog Jika ditemukan : likes(john,X):-is_female(X),owns(X,Y),isa_cat(Y).
Dengan kata lain :
john likes X:- X is_female, X owns Y, Y isa_cat.

















NOMOR 2 =

Define and test a predicate which takes two arguments, both numbers, and calculates and outputs the following values :

a. their average

b. the square root of their product

c. the larger of a and b










ini blog Dian,Eryka,April

dian           : http://diananggraeni.blog.com/

eryka         : http://erykadyana.blog.com/

april          : http://aprilliasyafitrie.blog.com/

Friday, October 23, 2009

EXPERT SYSTEM

An expert system is software that attempts to provide an answer to a problem, or clarify uncertainties where normally one or more human experts would need to be consulted. Expert systems are most common in a specific problem domain, and is a traditional application and/or subfield of artificial intelligence. A wide variety of methods can be used to simulate the performance of the expert however common to most or all are 1) the creation of a so-called "knowledgebase" which uses some knowledge representation formalism to capture the Subject Matter Expert's (SME) knowledge and 2) a process of gathering that knowledge from the SME and codifying it according to the formalism, which is called knowledge engineering. Expert systems may or may not have learning components but a third common element is that once the system is developed it is proven by being placed in the same real world problem solving situation as the human SME, typically as an aid to human workers or a supplement to some information system.


As a premiere application of computing and artificial intelligence, the topic of expert systems has many points of contact with general systems theory, operations research, business process reengineering and various topics in applied mathematics and management science.


ADVANTAGES AND DISADVANTAGES

Advantages:


  * Provides consistent answers for repetitive decisions, processes and tasks
  * Holds and maintains significant levels of information
  * Encourages organizations to clarify the logic of their decision-making
  * Never "forgets" to ask a question, as a human might
  * Can work round the clock
  * Can be used by the user more frequently
  * A multi-user expert system can serve more users at a time

Disadvantages:

  * Lacks common sense needed in some decision making
  * Cannot make creative responses as human expert would in unusual circumstances
  * Domain experts not always able to explain their logic and reasoning
  * Errors may occur in the knowledge base, and lead to wrong decisions
  * Cannot adapt to changing environments, unless knowledge base is changed

Types of problems solved by expert systems

Expert systems are most valuable to organizations that have a high-level of know-how experience and expertise that cannot be easily transferred to other members. They are designed to carry the intelligence and information found in the intellect of experts and provide this knowledge to other members of the organization for problem-solving purposes.

Typically, the problems to be solved are of the sort that would normally be tackled by a medical or other professional. Real experts in the problem domain (which will typically be very narrow, for instance "diagnosing skin conditions in human teenagers") are asked to provide "rules of thumb" on how they evaluate the problems, either explicitly with the aid of experienced systems developers, or sometimes implicitly, by getting such experts to evaluate test cases and using computer programs to examine the test data and (in a strictly limited manner) derive rules from that. Generally, expert systems are used for problems for which there is no single "correct" solution which can be encoded in a conventional algorithm — one would not write an expert system to find shortest paths through graphs, or sort data, as there are simply easier ways to do these tasks.

Simple systems use simple true/false logic to evaluate data. More sophisticated systems are capable of performing at least some evaluation, taking into account real-world uncertainties, using such methods as fuzzy logic. Such sophistication is difficult to develop and still highly imperfect.




Expert systems versus problem-solving systems

The principal distinction between expert systems and traditional problem solving programs is the way in which the problem related expertise is coded. In traditional applications, problem expertise is encoded in both program and data structures. In the expert system approach all of the problem related expertise is encoded in data structures only; no problem-specific information is encoded in the program structure. This organization has several benefits.

An example may help contrast the traditional problem solving program with the expert system approach. The example is the problem of tax advice. In the traditional approach data structures describe the taxpayer and tax tables, and a program in which there are statements representing an expert tax consultant's knowledge, such as statements which relate information about the taxpayer to tax table choices. It is this representation of the tax expert's knowledge that is difficult for the tax expert to understand or modify.

In the expert system approach, the information about taxpayers and tax computations is again found in data structures, but now the knowledge describing the relationships between them is encoded in data structures as well. The programs of an expert system are independent of the problem domain (taxes) and serve to process the data structures without regard to the nature of the problem area they describe. For example, there are programs to acquire the described data values through user interaction, programs to represent and process special organizations of description, and programs to process the declarations that represent semantic relationships within the problem domain and an algorithm to control the processing sequence and focus.

The general architecture of an expert system involves two principal components: a problem dependent set of data declarations called the knowledge base or rule base, and a problem independent (although highly data structure dependent) program which is called the inference engine.


Individuals involved with expert systems

There are generally three individuals having an interaction with expert systems. Primary among these is the end-user; the individual who uses the system for its problem solving assistance. In the building and maintenance of the system there are two other roles: the problem domain expert who builds and supplies the knowledge base providing the domain expertise, and a knowledge engineer who assists the experts in determining the representation of their knowledge, enters this knowledge into an explanation module and who defines the inference technique required to obtain useful problem solving activity. Usually, the knowledge engineer will represent the problem solving activity in the form of rules which is referred to as a rule-based expert system. When these rules are created from the domain expertise, the knowledge base stores the rules of the expert system.

RULE BASED EXPERT SYSTEMS


A rule-based expert system is an expert system (see intro) which works as a production system in which rules encode expert knowledge.
Most expert systems are rule-based. Alternatives are 
frame-based - knowledge is associated with the objects of interest and reasoning consists of confirming expectations for slot values. Such systems often include rules too. 
model-based, where the entire system models the real world, and this deep knowledge is used to e.g. diagnose equipment malfunctions, by comparing model predicted outcomes with actual observed outcomes
case-based - previous examples (cases) of the task and its solution are stored. To solve a new problem the closest matching case is retrieved, and its solution or an adaptation of it is proposed as the solution to the new problem.


Typical Expert System Architecture(from Luger and Stubblefield)


Data-driven Rule-based Expert Systems
Use Forward Chaining:
Given a certain set of facts in WM, use the rules to generate new facts until the desired goal is reached.
To forward chain the inference engine must:
1. Match the condition patterns of rules against facts in working memory.
2. If there is more than one rule that could be used (that could "fire"), select which one to apply (this is called conflict resolution)
3. Apply the rule, maybe causing new facts to be added to working memory
4. Halt when some useful (or goal) conclusion is added to WM (or until all possible conclusions have been drawn.)


Goal-driven Rule-based Expert Systems
Use Backward Chaining:
Work backwards from a hypothesised goal, attempting to prove it by linking the goal to the initial facts.
To backward chain from a goal in WM the inference engine must:
1. Select rules with conclusions matching the goal.
2. Replace the goal by the rule's premises. These become sub-goals.
3. Work backwards till all sub-goals are known to be true -
  either they are facts (in WM)
 or the user provides the information.


Example
A production system IDENTIFIER, which identifies animals.
R1 IF the animal has hair
 THEN it is a mammal
R2 IF the animal gives milk
 THEN it is a mammal
R3 IF the animal has feathers
 THEN it is a bird
R4 IF the animal flies
  the animal lays eggs
 THEN it is a bird
R5 IF the animal is a mammal
  the animal eats meat
 THEN it is a carnivore
R6 IF the animal is a mammal
  the animal has pointed teeth
  the animal has claws
  the animal's eyes point forward
 THEN it is a carnivore
R7 IF the animal is a mammal
  the animal has hooves
 THEN it is an ungulate
R8 IF the animal is a mammal
  the animal chews cud
 THEN it is an ungulate AND
  it is even-toed
R9 IF the animal is a carnivore
  the animal has a tawny colour
  the animal has dark spots
 THEN it is a cheetah

R10 IF the animal is a carnivore
  the animal has a tawny colour
  the animal has black stripes
 THEN it is a tiger
R11 IF the animal is an ungulate
  the animal has long legs
  the animal has a long neck
 THEN it is a giraffe
R12 IF the animal is an ungulate
  the animal has a white colour
  the animal has black stripes
 THEN it is a zebra
R13 IF the animal is a bird
  the animal does not fly
  the animal has long legs
  the animal has a long neck
  the animal is black and white
 THEN it is an ostrich
R14 IF the animal is a bird
  the animal does not fly
  the animal swims
  the animal is black and white
 THEN it is a penguin
R15 IF the animal is a bird
  the animal is a good flier
 THEN it is an albatross


PROBLEM:
Given these facts in working memory initially:
 the animal gives milk
the animal chews its cud
the animal has long legs
the animal has a long neck
Establish by forward chaining that the animal is a giraffe.
Given the facts that:
 the animal has hair
the animal has claws
the animal has pointed teeth
the animal's eyes point forward
the animal has a tawny colour
the animal has dark spots
Establish by backward chaining that the animal is a cheetah.
[HINT: start with R9, first subgoal : the animal is a carnivore etc.]
Goal-driven search is suggested if:
A goal or hypothesis is given in the problem statement or can be easily formulated
(theorem-proving, diagnosis hypothesis testing).
There are a large number of rules that match the facts, producing a large number of conclusions - choosing a goal prunes the search space.
Problem data are not given (or easily available) but must be acquired as necessary (e.g. medical tests).

Data-driven search is suggested if:
All or most of the data is given in the problem statement (interpretation problems)
Large number of potential goals but few achievable in a particular problem instance.
It is difficult to formulate a goal or hypothesis.

Data-driven search can appear aimless but produces all solutions to a problem (if desired)
Mixed reasoning is also possible - facts get added to the WM and sub-goals get created until all the sub-goals are present as facts.


Explanation Facility in Expert Systems

Rule-based systems can be designed to answer questions like
WHY do you want to know this fact ? (i.e. where is the reasoning going?)
HOW did you deduce this fact ? (i.e. how did we get here?)
Explanation facilities are useful for debugging a rulebase but also for instilling confidence in users of the ES.
A tracer module records the rules that have been used. To answer HOW questions these rules are searched for one where the fact in question is a consequent (action/then part).
(see MYCIN case study)
The production system architecture provides the essential basis for explanation facility, and the facility contributes to the success and popularity of rule-based ES.


Handling Uncertainty in Expert Systems

Uncertainty arises from abductive rules, heuristic rules or missing or unreliable data.
ABDUCTION: ES rules are frequently not sound logically, but are abductive. The abductive rule
 if the engine does not turn over and
  the lights do not come on
 then the problem is battery or cables.
is not always right, but would be typical of a car diagnosis system. Its converse, while not so useful is logically sound :
 if the problem is battery or cables
 then the engine does not turn over and
  the lights do not come on

Abductive reasoning is very important in diagnosis - diseases cause symptoms, but we have sympoms and want to work back to the cause.
To reason with uncertainty, we attach confidence measures to facts and to rules. We need mechanisms to combine these measures.

Handling uncertainty in rule-based expert systems
Three situations need to be handled.
(1) If A and B and C then …
If my confidence in A is x and in B is y and in C is z how confident am I about their conjunction (A and B and C)?
(2) If D then E
If my confidence in D is x how confident can I be in E?
(3) If the same fact F is deduced from (two) separate rules with confidences x and y, how confident am I in F?  
A. Simple (Conservative) Rules
(1) Confidence in the conjunction is
min (x, y z) a chain is as strong as its weakest link
(2) Confidence in rule conclusion is 
x . a a is the rule's attenuation factor
(3) Confidence in the multiply derived fact is
 max (x, y) a conclusion is no more certain than the strongest supporting argument.
B. Bayesian Probability Theory Based
Confidence measures are probabilities.
(1) Confidence in conjunction is = x . y . z
(2) Confidence in a rule is based on Bayes theorem 

(there should be a summation symbol on the bottom line)
which relates 
P(Di|S) the probability of having disease i if you have the symptom S,
to measures of 
P(Di) the probability of having disease i in general,
P(S|Di) the probability of having the symptom S if you have disease i, and 
P(S|Dk) for all possible diseases Dk, the probability of having symptom S if you have diseases Dk. 

(Diseases are hypotheses; symptoms are evidence.)


Difficulties with Bayes' Theorem:

Bayes theorem assumes that relationships between evidence and hypotheses are independent of one another. (e.g. the probability of someone who has flu having a sore throat and the probability of someone who has flu having a temperature, should be independent. But are they ?)

Probabilities should be collected statistically, and kept up to date with all new discoveries about diseases and their symptoms. This is impractical.

Bayes-based probability is not a good way to model uncertainty in medical diagnosis systems.
Nonetheless, doctors feel that they can make informed assessment of their confidence in their heuristic rules.


C. Stanford Certainty Factor Algebra
(See also MYCIN notes.)
CF (H|E) is the certainty factor of hypothesis H given evidence E.
-1 < CF (H|E) < 1
strong evidence strong evidence
against the hypothesis for the hypothesis

(1) Confidence in the conjunction is
 min (x, y, z)
(2) Confidence in rule conclusion is 
 x . CF (R) CF (R) is certainty factor associated with this conclusion of the rule.
(3) Confidence in the multiply derived fact is
  x + y - (x * y) if both are positive
 x + y + (x * y) if both are negative
? = x + y . otherwise
  1 - min (|x|, |y|)
Note: These formulae leave -1 < CF < 1
 Combining contradictory rules cancels out the CF
 CFs increase montonically as we add evidence
Other theories for handling uncertainty
Zadeh's Fuzzy Sets - a theory of possibility that tries to measure the vagueness of English statements (e.g. "Ann is tall")
Dempster-Schafer Belief Functions  
All these theories are numeric which does not seem to be the way humans reason with uncertainty.
Non-monotonic reasoning is a completely different approach which allows you to proceed with the most reasonable assumption based on uncertain information and to change the assumption (and conclusions that have arisen from it) if the assumption becomes unreasonable. (Truth maintenance systems.)
(Monotonic reasoning systems only allow knowledge/info to be added, whereas humans delete information that is found tobe untrue.)


Expert System Shells
An expert system shell is an expert system with an empty knowledge base, i.e.
An inference engine
User interface module
Tracer/explanation module
Knowledge base (rule) editor
Etc.

EXSYS is a shell, KEE, OPS5, KAS, …
EMYCIN is the shell of MYCIN

It is important to start with a shell with a suitable control strategy.
Recent trends are towards shells that include multiple engines, making them more flexible.


Case Study : MYCIN
An example Goal-driven Medical Diagnostic Expert System

(taken from Luger and Stubblefield section 8.4)
Purpose: 
Diagnose and recommend treatment for meningitis and bacteremia (more quickly than definitive lab tests).
Explore how human experts reason with missing and incomplete information.
History
mid-late '70s
50 person years
Stanford medical school
Comprehensively evaluated
Never used clinically
Widely documented ("Rule-based expert systems" Buchanan and Shortliffe, Stanford 1984, a collection of publications on MYCIN).
Representation
Facts:
(ident organism-1 klebsiella .25)
 there is evidence (.25) that the identity of organism-1 is klebsiella
(sensitive organism-1 penicillin -1.0)
 it is known that org-1 is NOT sensitive to penicillin.
Rules: condition-action pairs
  Condition is a conjunction (AND) of facts
IF: (AND (same-context infection 
  primary-bacteremia)
 (membf-context site sterilesite)
 (same-context portal GI))
THEN: (conclude context-ident bacteroid 
  tally .7)
 If the infection is primary bacteremia and the site of the culture is a sterile one and the suspected portal of entry is GI tract then there is suggestive evidence (.7) that infection is bacteroid.
Consequent (then-part) can
Add facts to database
Write to terminal
Change a value in a fact, or its certainty
Lookup a table
Execute a LISP procedure
Operation:
Routine questions

Specific questions about symptoms

Depth-first goal driven consideration 
of each "known" organism

Terminates "depth-search" when certainty measures get too low.
Selection criterion is to maximise certainty - if a rule can prove a goal with certainty 1 then no more rules need be considered.
Goal-driven so that questions appear to be directed - less frustrating, more confidence building for the user.
English-like interaction (see handout).
Answers WHY by printing the rule under consideration.
Exhaustive consideration of possible infections - patient may have more than one.
Uncertainty in MYCIN

If A: stain is gram positive
and B: morphology is coccus
and C: growth conformation is chains
then there is suggestive evidence (0.7) that 
H: organism is streptococcus 

0.7 is the measure of increase of belief (MB) of H given evidence A and B and C.
MB ranges 0 to 1. 
Assigned by subjective judgement usually.
As a guide:
  1 if P(H)=1
 MB(H|E) = max[P(H|E),P(H)] - P(H) otherwise
  max[1,0] - P(H)
Measures of disbelief also allowed. These also range 0 to 1.
  1 if P(H)=1
 MD(H|E) = min[P(H|E),P(H)] - P(H) otherwise
  min[1,0] - P(H)
Note if E and H are independent, E does not change the belief in H:
P(H|E) = P(H), so MB = MD = 0.
MB(H|E) should only be 1 if E logically implies H.
Initially each hypothesis has MB=MD=0.
As evidence is accumulated these are updated.
At the end a certainty factor CF = MB-MD is computed for each hypothesis.
The largest absolute CF values used to determine appropriate therapy. Weakly supported hypotheses |CF| < 2 are ignored.

MYCIN's handling of uncertainty is an ad-hoc method (based on probability). But it seems to work as well as more formal approaches.



Tuesday, October 13, 2009

TUTORIAL (matematika diskrit)

panda(jessica) .
bear(koko) . panda(lei) .
panda(micha) . bear (harry) .
panda(momo) .
bear(ben) . bear(ray).



hasil setelah diprogram di prolog :
Warning: (c:/documents and settings/mulyono/desktop/hasil.pl:2):
Clauses of panda/1 are not together in the source-file
ERROR: c:/documents and settings/mulyono/desktop/hasil.pl:3:15: Syntax error: Operator expected
Warning: (c:/documents and settings/mulyono/desktop/hasil.pl:5):
Clauses of bear/1 are not together in the source-file
% c:/Documents and Settings/Mulyono/Desktop/hasil.pl compiled 0.00 sec, 1,940 bytes
Welcome to SWI-Prolog (Multi-threaded, Version 5.4.7)
Copyright (c) 1990-2003 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

1 ?- panda(momo).

Yes
2 ?- bear(koko).

Yes
3 ?- panda(koko).

No
4 ?- bear(momo).

No
5 ?- panda(X).

X = jessica ;

X = lei ;

X = micha ;

X = momo ;

No
6 ?- bear(Y).

Y = koko ;

Y = ben ;

Y = ray ;

No
7 ?- panda(Y).

Y = jessica ;

Y = lei ;

Y = micha ;

Y = momo ;

No
8 ?- bear(X).

X = koko ;

X = ben ;

X = ray ;

No
9 ?- panda(Y), bear(X).

Y = jessica
X = koko ;

Y = jessica
X = ben ;

Y = jessica
X = ray ;

Y = lei
X = koko ;

Y = lei
X = ben ;

Y = lei
X = ray ;

Y = micha
X = koko ;

Y = micha
X = ben ;

Y = micha
X = ray ;

Y = momo
X = koko ;

Y = momo
X = ben ;

Y = momo
X = ray ;

No
10 ?- listing(panda).


panda(jessica).
panda(lei).
panda(micha).
panda(momo).

Yes
11 ?- listing(bear).


bear(koko).
bear(ben).
bear(ray).