You are on page 1of 43

JESS:Java Expert

System Shell

Course IFT6802
Student ZHENG ZHEN

March 12, 2003

UMontreal ift6802

Overview
What is Jess?
Jess is a tool for building a type of
intelligent software called Expert Systems.
An Expert System:
a set of rules can be repeatedly applied to
a collection of facts
Developed by Sandia Laboratories
March 12,

UMontreal ift6802

facts in Jess look like:


(person "Bob Smith" Male 35) or
(person (name "Bob Smith") (gender Male)
(age 34))
slots

rules in Jess look like:


A rule has two parts: LHS pattern => RHS action
(defrule example-3
(not-b-and-c ?n1&~b ?n2&~c)
(different ?d1 ?d2&~?d1)
=>
(printout t "Found what I wanted!" crlf))
March 12,

UMontreal ift6802

What are advantages?


Jess is a rule engine
Jess is a scripting environment for Java
Jess call Java
Jess is faster than some popular expert
system shells written in C
Jess is easy to extend with new commands

March 12,

UMontreal ift6802

How to start?
Start as command-line interface
java -classpath jess.jar jess.Main

Start as console-style GUIs


java -classpath jess.jar jess.Console

March 12,

UMontreal ift6802

Introduction
Basics:
Atom letters, numbers and $*=+/<>_?#. case
sensitive Numbers, Strings, Comments (;)
Lists fundamental unit of syntax in Jess ( a b c),
variables (?) + atoms : ?x
multivariable $+ variable: $?y
(defrule example
(grocery-list $?list) => (printout t "I need to buy " $?list crlf))
Jess> (assert (grocery-list eggs milk bacon))

Global variable : ?*x* or ?*all-values*


March 12,

UMontreal ift6802

Function: can be defined with two ways


1) define a function directly
(deffunction max (?a ?b)
(if (> ?a ?b) then ?a else ?b))
Function calls are simply lists
Jess> (printout t "The greater of 3 and 5 is " (max
3 5) crlf)
The greater of 3 and 5 is 5
2) "wrap" extra code around any Jess function
(defadvice before + (bind $?argv (create$ $?argv
1)))
Jess> (+ 2 2)
5
Variables
Function
Examples:

March 12,

UMontreal ift6802

Java reflection
Jess can create and manipulate Java objects
directly

1)

(bind ?ht (new java.util.Hashtable))


Jess> (call ?ht put "key1" Apple")
Jess> (?ht get "key1")
Apple"
2) Jess access member variables of Java objects
Jess> (bind ?pt (new java.awt.Point))
<External-Address:java.awt.Point>
Jess> (set-member ?pt x 37)
Jess> (set-member ?pt y 42)
Jess> (get-member ?pt x)
37

March 12,

UMontreal ift6802

37
42

access static members by using the name of the class


Jess> (get-member System out)
Jess can import either a whole package
using (import java.io.* )
or a single class using
(import java.awt.Button)
Type conversion (Rete Utilities, RU)
null

'nil'

boolean/Boolean

'TRUE' ,'FALSE'

void

'nil'

byte, short, int/wrappers

RU.INTEGER

String

RU.STRING

double, float /wrappers

RU.FLOAT

An array

multifield

Char/Character

RU.ATOM

long / Long

RU.LONG

anything else

RU.EXTERNAL_ADDRESS

March 12,

UMontreal ift6802

Facts
Facts is one of the most important parts of Jess
(1) ordered facts
Facts
(2) unordered facts
(3) definstance facts
(1): (assert (person "Bob Smith" Male 35) )
(2): using the deftemplate define the slots
(deftemplate person
(slot name )
(slot age )
(slot gender) )
after that assert unordered fact:
(assert (person (name "Bob Smith") (age 34) (gender
Male)))

March 12,

UMontreal ift6802

10

(3):
template similarity
Java Beans
slots similarity
properties
Jess provides:
defclass Java Beans
Jess template
definstance Bean representation
fact base
import java.io.Serializable;
public class ExampleBean implements Serializable {
private String m_name = "Bob";
public String getName() { return m_name; }
public void setName(String s) { m_name = s; }
}// end of class

Jess> (defclass simple ExampleBean)


Jess> (ppdeftemplate simple)

March 12,

UMontreal ift6802

11

Jess> (bind ?sb (new ExampleBean))


Jess> (definstance simple ?sb static)
Jess> (facts)

dynamic

f-0 (MAIN::simple
(class <External-address:java.lang.Class>)
(name "Bob")
(OBJECT <External-Address:ExampleBean>))
For a total of 1 facts
A fact representing the Bean appears in the
knowledge base
Examples:

March 12,

Facts

Console

UMontreal ift6802

12

Rules
Rules can take actions based on the contents of facts
It is similar to if then, but
Jess> (watch all)
Jess> (defrule do-change-baby
"If baby is wet, change baby's diaper.
(baby-is-wet) => (change-baby))
Jess> (deffunction change-baby ()
(printout t "Baby is now dry" crlf))
Jess> (assert (baby-is-wet))
Jess> (run)
FIRE 1 MAIN::do-change-baby f-1 Baby is now
dry
<== Focus MAIN 1

March 12,

UMontreal ift6802

13

Basic Patterns
Jess> (defrule example
(different ?d1 ?d2&~?d1)
(same ?s ?s)
(more-than-one-hundred ?m&:(> ?m 100))
(red-or-blue red|blue)
(one-more ?X =(+ ?X 1))
=>
(printout t "Found what I wanted!" crlf))
Which facts can fire this rule?
1. (different 100 11) 2. (same d d) 3. (red-or-blue
white)
4. (more-than-one-hundred 101) 5. (one-more 72
73)

March 12,

UMontreal ift6802

14

Pattern bindings
A pattern-binding variable used to retract /modify the fact
Jess> (defrule example-5 ?fact <- (a "retract me") => (retract ?
fact))
1. Jess> (assert (a "retract me"))
==> f-1 (MAIN::a "retract me")
==> Activation: MAIN::example-5 : f-1
<Fact-1>
If we try assert the fact again, Jess prompt FALSE
2. Jess> (assert (a "retract me"))
FALSE
3. Jess> (run)
FIRE 1 MAIN::example-5 f-1
<== f-1 (MAIN::a "retract me")
<== Focus MAIN
1

March 12,

UMontreal ift6802

15

4. Jess> (run)
0
5. Jess> (assert (a "retract me"))
==> f-2 (MAIN::a "retract me")
==> Activation: MAIN::example-5 : f-2
<Fact-2>
6. Jess> (facts)
f-0 (MAIN::initial-fact)
f-2 (MAIN::a "retract me")
For a total of 2 facts.
Where is the f-1?

pattern-binding variable ?fact <---- fact ID


<----a reference to a jess.Fact object
March 12,

UMontreal ift6802

16

Salience
Salience is a kind of rule priority, each rule has one
Salience high
Activated
Activated
Activated
.
.
Activated

Rule1
Rule2
Rule3
Rule n

be fired
if same salience
then conflict resolution strategy

Salience low
Salience values can be integers, global variables, or function calls

Jess> (defrule example-6


(declare (salience -100)) ... => .)
Or call
(set-salience-evaluation ..)
March 12,

UMontreal ift6802

17

Conditional Element (CE.)


'and' used to construct complex logical conditions with or and not
'or'
Jess> (defrule or-example-1 (or (a) (b) (c)) =>)
MAIN::or-example-1: =1+1+1+t
MAIN::or-example-1&1: +1+1+1+t
MAIN::or-example-1&2: +1+1+1+t
TRUE

. (1)
. (2)
. (3)

Jess> (assert (a) (b) (c))


Jess> (printout t (run) crlf)
FIRE 1 MAIN::or-example-1 f-3
FIRE 2 MAIN::or-example-1 f-2
FIRE 3 MAIN::or-example-1 f-1
3
(1),(2) and (3) are 3 separate sub-rules

March 12,

UMontreal ift6802

18

'not
Jess> (defrule forall-example (not (and (a ?x) (not (b ?
x)))) =>)
a => b ; a V b

cannot define any variables used in subsequent patterns


only evaluated a fact matching it exists
if a not CE is
the first on a rule's LHS (not () =>)
the first in an and group (or (..) (not(..)) ..=>)
the only pattern on a given branch of an or group
then
(initial-fact) is inserted as preceding pattern
Why usually write (reset) before (run) in the Jess file?

March 12,

UMontreal ift6802

19

Rearranging not CE together with and and or


Based on DeMorgan's rules for logical operations
1. (not (and (x) (y))) => (or (not (x)) (not (y)))
(x y) => (x) (y)
2. (not (or (x) (y))) => (and (not (x)) (not (y)))
(x y) => (x) (y)
Two constraints of Jess rule LHS:
1. or CE must be at the top level
2. not CE must apply DeMorgan's rules
Conjunctive Normal Form
atom exclude , conjunct with

March 12,

UMontreal ift6802

20

'test'
Jess> (deftemplate person (slot age))
Jess> (defrule example-8
(person (age ?x))
(test (> ?x 60))
=>
(printout t ?x " is over 60!" crlf))
Jess> (assert (person (age 65)))
==> f-8 (MAIN::person (age 65))
==> Activation: MAIN::example-8 : f-8,
<Fact-8>
Jess> (run)
FIRE 1 MAIN::example-8 f-8,
65 is over 60!
March 12,

UMontreal ift6802

21

test CE is evaluated
as long as evaluated the preceding pattern
so
Jess> (defrule rule_1 (foo ?X)
(test (> ?X 3)) =>)
same as
Jess> (defrule rule_2 (foo ?X&:(> ?X 3)) =>)

therefor
IF a test CE is the first pattern on the LHS , or
the first pattern in a branch of an or CE
(initial-fact) must insert as the "preceding
pattern"
Why usually write (reset) before (run) in the Jess file?

March 12,

UMontreal ift6802

22

'logical'
logical CE specify logical dependencies among facts
Jess> (defrule rule-1 (logical (faucet-open))
=> (assert (water-flowing)))
Jess> (assert (faucet-open))
Jess> (run)
Jess> (facts)
f-0 (MAIN::faucet-open)
f-1 (MAIN::water-flowing)
For a total of 2 facts.

Jess> (watch facts)


Jess> (retract (fact-id 0))
<== f-0 (MAIN::faucet-open)
<== f-1 (MAIN::water-flowing)
TRUE

logical CE must be the first patterns in the rule

March 12,

UMontreal ift6802

23

'unique'
Jess> (deftemplate tax-form (slot social-security-number))
Jess> (deftemplate person (slot social-security-number)
(slot name))
Jess> (defrule unique-demo
(tax-form (social-security-number ?num))
(unique (person (social-security-number ?num)
(name ?name)))
=>
(printout t "Auditing " ?name "..." crlf))

unique CE hint to Jess that only one can have a


given SSN
so Jess dont look further
in the same patten,
unique dont combine with either test or not
CEs
unique is quite similar to Prologs ! (cut)

March 12,

UMontreal ift6802

24

'exists'
Jess> (defrule exists-demo (exists (honest ?))
=>
(printout t "There is at least one honest
man!" crlf))
(exists (A)) same as (not (not (A))).
in the same pattern ,
exists may not be combined with a test
CE.
Combination of various CE can provide the
powerful flexible inference engine
March 12,

UMontreal ift6802

25

Forward and backward chaining


1) supports both forward and backward chaining
2) To use backward chaining in Jess, use like
Jess> (do-backward-chaining factorial)
Prolog is backwards chaining: given the rules
human(Socrates). mortal(X) :- human(X)
Jess, though, is forwards chaining. Here, you have
Jess> (assert (human Socrates))
Jess> (defrule mortal (human ?X)
=>
(assert (mortal ?X)))
Jess> (watch facts)
Jess> (run)
==> f-1 (MAIN::mortal Socrates) 1

March 12,

UMontreal ift6802

26

Defqueries
defquery create a special kind of rule with no RHS
Jess> (defquery search (declare (variables ?X)) (foo ?
X ?Y))
Jess> (deffacts data (foo blue red) (bar blue green)
(foo blue pink) (foo red blue)
(foo blue blue) (foo orange yellow)
(bar blue purple))
Jess> (reset)
Jess> (bind ?it (run-query search blue))
Jess> (while (?it hasNext)
(bind ?token (call ?it next))
(bind ?fact (call ?token fact 1))
(bind ?slot (fact-slot-value ?fact __data))
(bind ?datum (nth$ 2 ?slot))
(printout t ?datum crlf))
red pink blue FALSE

March 12,

UMontreal ift6802

27

Defmodules
Modules divide rules and templates into distinct
groups
By default, current module is "MAIN::
Jess> (defmodule WORK)
Jess> (deftemplate WORK::job (slot
salary))
TRUE
Jess> (list-deftemplates WORK)
WORK::job
For a total of 1 deftemplates.
Jess> (get-current-module)
WORK

The MAIN is global namespace for templates.


March 12,

UMontreal ift6802

28

Focus: only rules in the focus module will fire


focus module independent from current module
Jess> (defmodule DRIVING)
Jess> (defrule get-in-car
=>
(printout t "Ready to go!" crlf))
Jess> (reset)
Jess> (run)
0
Why not? Which is current module?
Jess> (focus DRIVING)
MAIN
Jess> (run)
Ready to go!
1

March 12,

UMontreal ift6802

29

Returning from a rule RHS


return terminates the execution of RHS and
focus module popped from the focus stack
using focus call a module from a rule's RHS
using return return from the call like a subroutine

March 12,

UMontreal ift6802

30

Jess vs. Java


use Jess library in Java
import jess.*;
public class ExSquare {
public static void main(String[] unused)
{
try {
Rete r = new Rete();
r.executeCommand("(deffunction square (?n) (return (* ?n ?n)))");
Value v = r.executeCommand("(square 3)"); // Prints '9'
System.out.println(v.intValue(r.getGlobalContext()));
} catch (JessException ex) { System.err.println(ex); }
}
}
C:\> java ExSquare
9

March 12,

UMontreal ift6802

31

jess.Rete class : the rule engine itself


1. each jess.Rete object : an independent reasoning engine
2. jess.Rete object in a multithreaded environment
assert or retract in a given jess.Rete object at a time
3. Call Jess functions directly in Java
run(), reset(), clear(), assertFact(Fact),
retract(Fact), retract(int), and halt().
4. Executing other Jess commands
Rete class's executeCommand(String cmd) a parseable String
returns the jess.Value object & interpreted in the global context

March 12,

UMontreal ift6802

32

5. Value resolution
static values (atoms, numbers, strings)
jess.Value
dynamic values (variables, function calls)
dynamic values need
to be interpreted in a particular context before use
jess.Value.intValue(jess.Context) is self-resolving
jess.Value. type() return RU.VARIABLE for a jess.Value object
jess.Value. resolveValue() resolve the return value

March 12,

UMontreal ift6802

33

6. Transferring

values between Jess and Java

On java side methods are available in the jess.Rete


public
public
public
public

Value store(String name, Value val);


Value store(String name, Object val);
Value fetch(String name);
void clearStorage();

On jess side :
(store <name> <value>)
(fetch <name>) (clear-storage)

March 12,

UMontreal ift6802

34

import jess.*;
public class ExFetch {
public static void main(String[] unused) throws
JessException {
Rete r = new Rete();
r.store("DIMENSION", new java.awt.Dimension(10, 10));
r.executeCommand("(defclass dimension
java.awt.Dimension)");
r.executeCommand("(definstance dimension
(fetchDIMENSION) static)");
r.executeCommand("(facts)");
}
}
C:\> java ExFetch
f-0 (MAIN::dimension (class <ExternalAddress:java.lang.Class>) (height 10.0) (size <ExternalAddress:java.awt.Dimension>) (width 10.0) (OBJECT
<External-Address:java.awt.Dimension>))
For a total of 1 facts.

March 12,

UMontreal ift6802

35

7. Adding new functions to the Jess


by implements interface Rete.addUserfunction()
import jess.*;
public class ExMyUpcase implements Userfunction {
public String getName() { return "my-upcase"; }
public Value call(ValueVector vv, Context context)
throwsJessException
{ return new
Value(vv.get(1).stringValue(context).toUpperCase(),
RU.STRING); }
}

C:\> java ExMyUpcase


Jess> (load-function ExMyUpcase)
Jess> (my-upcase foo)
"FOO"

March 12,

UMontreal ift6802

36

Jess vs. Jade


Jade : Multi-agent platform
Jess + Jade : Multi-intelligent agent platform
Jade call Jess = Java call Jess
Jess template ~ Jade ontology
public class BasicJessBehaviour extends CyclicBehaviour{
.
public class JessSend implements Userfunction {
..
jess.executeCommand(ACLJessTemplate());
jess.executeCommand("(deftemplate MyAgent (slot name))");
jess.addUserfunction(new JessSend(myAgent,this));
jess.executeCommand("(deffacts MyAgent \"All facts about this
agent\" (MyAgent (name " + myAgent.getName() + ")))");
.

March 12,

UMontreal ift6802

37

Jess VS. Protege


Difficult manage large/complex ontologies
Ontology editors should be programmable
Difficult to integrate problem solving and ontology development
OO languages/shells need an graphical counterpart

Protg:
Knowledge acquisition and ontology development tool
Developed by SMI, Stanford University
http://protege.stanford.edu/

JessTab Combining two popular systems


JessTab is a tab plug-in for running Jess inside Protg
March 12,

UMontreal ift6802

38

Jess console window in Protg

March 12,

UMontreal ift6802

39

Mirroring Jess definitions in Protg knowledge bases

March 12,

UMontreal ift6802

40

Editing Jess definitions in Protg

March 12,

UMontreal ift6802

41

Agent frameworks
Jess + Jade + Protg = JadeJessProtg
FuzzyJess

PrologTab
JessTab

More
Jess
extension
s

FloraTab

Jess

Protg
JadeJessProtege
Your tab

JADE

More
Protg
plug-ins

Your system
March 12,

UMontreal ift6802

42

References
http://www.iro.umontreal.ca/~vaucher/ift6802/Guide.html
Obtain Jess
Download from http://herzberg.ca.sandia.gov/jess/
License required (commercial or free academic)
Compilation required
Get JessTab
Download from http://www.ida.liu.se/~her/JessTab/
Obtain Protg
Download from http://protege.stanford.edu/

March 12,

UMontreal ift6802

43

You might also like