Presentation is loading. Please wait.

Presentation is loading. Please wait.

JESS-JAVA Integration

Similar presentations


Presentation on theme: "JESS-JAVA Integration"— Presentation transcript:

1 JESS-JAVA Integration csandru@info.uvt.ro
Intelligent Systems JESS-JAVA Integration

2 Programming with JESS Reference: http://www.jessrules.com
Pure Jess language scripts. No Java code at all. Pure Jess language scripts, but the scripts access Java APIs. Mostly Jess language scripts, but some custom Java code in the form of new Jess commands written in Java. Half Jess language scripts, with a substantial amount of Java code providing custom commands and APIs; main() provided by Jess. Half Jess language scripts, with a substantial amount of Java code providing custom commands and APIs; main() provided by Java. Mostly Java code, which loads Jess language scripts at runtime. All Java code, which manipulates Jess entirely through its Java API. JESS language AND JESS API

3 The Rete class The Rete class: import jess.Rete;
It is a rule engine with agenda, working memory and knowledge Thread safe Its methods are: JESS functions like: clear, reset, run, watch, assertFact, retract , modify, addDefRule, addDefTemplate, addDefModule, etc Persistence related functions: batch, bload, bsave Dynamic evaluation of expressions: eval Agenda inspection: listActivations, hasActivations Knowledge base inspection: listDefrules, listDeftemplates, listFacts, etc Query manipulation: runQueryStar Events listening: addJessListener, removeJessListener Various other: mark, store, fetch, add , remove, etc, etc

4 Sample code template public void start(){ //create an expert engine
Rete expertEngine = new Rete(); //load the expertise try { expertEngine.batch("bgExpert.clp"); } catch (JessException e) { System.out.println("Error loading the expertise: " +e.toString()); } expertEngine.reset(); System.out.println("Exception reseting the engine: " + e.toString()); //ADD OTHER CODE HERE //run the expertise expertEngine.run(); System.out.println("Exception running the engine: " + e.toString());

5 JESS listening Ability to listen on significant JESS events like:
Managing constructs Managing facts Agenda changes Commands execution Module focus RETE internals JessEvent.class JessListener.class

6 Listening for movements(1)
//create an ReTe engine Rete engine = new Rete(); try { //load the expertise engine.batch("blocks.clp"); //register a listener into the engine for //receiving moves MovesListener listener = new MovesListener(); engine.addJessListener(listener); engine.setEventMask(engine.getEventMask() | JessEvent.FACT); engine.reset(); engine.run(); } catch (JessException e) { System.out.println("Loading JESS code exception: " + e.toString()); }

7 Listening for movements(2)
private static final String BLOCK_SLOT = "block"; private static final String SUPPORT_SLOT = "support"; private static final String MOVE = "MAIN::move"; private class MovesListener implements JessListener{ public void eventHappened(JessEvent event) throws JessException { int eventType = event.getType(); //only process fact additions or modifications if ((eventType & JessEvent.FACT) != 0 && (eventType & JessEvent.REMOVED) == 0){ Fact fact = (Fact)event.getObject(); Deftemplate factTpl = fact.getDeftemplate(); //only look at moves if (factTpl.getName().equals(MOVE)){ Value block = fact.getSlotValue(BLOCK_SLOT); Value support = fact.getSlotValue(SUPPORT_SLOT); System.out.println("Moved on Java " + block.toString() + " on " + support.toString()); }

8 Jess Values Value.class Immutable
Types – type(): SYMBOL, STRING, INTEGER, SLOT, MULTISLOT, FACT, LIST, etc. See API docs. ValueFactory.class: provides appropriate Value objects of a specified type Rete engine = new Rete(); ValueFactory f = engine.getValueFactory(); Value v1 = f.get("foo", RU.SYMBOL);

9 Creating facts from Java
Rete r = new Rete(); r.eval("(deftemplate point \"A 2D point\" (slot x) (slot y))"); Fact f = new Fact("point", r); f.setSlotValue("x", new Value(37, RU.INTEGER)); f.setSlotValue("y", new Value(49, RU.INTEGER)); r.assertFact(f); r.eval("(deftemplate vector \"A named vector\" (slot name) (multislot list))"); Fact f = new Fact("vector", r); f.setSlotValue("name", new Value("Groceries", RU.SYMBOL)); ValueVector vv = new ValueVector(); vv.add(new Value("String Beans", RU.STRING)); vv.add(new Value("Milk", RU.STRING)); vv.add(new Value("Bread", RU.STRING)); f.setSlotValue("list", new Value(vv, RU.LIST));

10 Contexts Execution context for the evaluation of function calls and the resolution of variables May have a parent context The Rete objects have a global context (getGlobalContext()) The Values and Userfunctions may be evaluated in specific contexts: Value.intValue(context) Userfunction.call(args, context)

11 Adding commands to Jess
public class ExMyUpcase implements Userfunction { // The name method returns the name by which // the function will appear in Jess code. public String getName() { return "my-upcase"; } public Value call(ValueVector vv, Context context) throws JessException { String result = vv.get(1).stringValue(context).toUpperCase(); return new Value(result, RU.STRING); r.addUserfunction(new ExMyUpcase());

12 Reasoning about JAVA objects in JESS
import java.io.Serializable; public class Account implements Serializable { private float balance; public float getBalance() { return balance; } public void setBalance(float balance) { this.balance = balance; How to make objects subjects of LHS matching?

13 Shadow facts Unordered facts that serve as "bridges" to Java objects
Serve to put any Java object into Jess's working memory. (deftemplate account (declare (from-class Account))) - construct (defclass account Account) – function (definstance account (new Account “Name”) [static | dynamic | auto] ) (assert (Account (name “Test”))): no object created (add new Account “Other”): automatically creates a template called “Account”, a shadow fact and the account object (bind ?a (new Account “Third”)) (add ?a) Jess> (facts) f-0 (MAIN::Account (balance 0.0) (class <Java-Object:java.lang.Class>) (OBJECT <Java-Object:Account>))

14 Ensuring shadow facts consistency
(bind ?pObject (new Person “John” “B”)) (bind ?person (add ?pObject)) (modify ?person (name “Jack”)): pObject automatically updated (?pObject setName “Jack”): fact is not updated; need special update (update ?pObject)

15 Automatic updating public class Person {
PropertyChangeSupport pcs = new PropertyChangeSupport(this); public void setName(String name) { String temp = name; this.name = name; pcs.firePropertyChange("name", temp, name); } public void setBlood(String blood) { String temp = blood; this.blood = blood; pcs.firePropertyChange("blood", temp, blood); }; public void addPropertyChangeListener(PropertyChangeListener pcl) { pcs.addPropertyChangeListener(pcl); public void removePropertyChangeListener(PropertyChangeListener pcl) { pcs.removePropertyChangeListener(pcl);

16 Querying WM Allows for retrieving working memory objects/facts based on filters Iterator<Object> it = expertEngine.getObjects(new Filter() { public boolean accept(Object o) { return o instanceof Person; } }); while(it.hasNext()) { System.out.println("Person object in WM: " + ((Person) it.next()).getName());

17 Queries Defining queries Collect the result (defquery search-by-name
"Finds compatibilities for a given name" (declare (variables ?name)) (compatibility (who ?name) (with ?with&~”John”)) ) Collect the result QueryResult result = expertEngine.runQueryStar("search-by-name", new ValueVector().add(new Value(“Mathew”, RU.STRING))); while (result.next()) { System.out.println(name + " is compatible with: " + result.getString("with")); }

18 Marks in the working memory
Save a working memory status expertEngine.batch("bgExpert.clp"); expertEngine.reset(); expertEngine.addAll(getDonors()); //save this engine status for future resets WorkingMemoryMarker initialStatus = expertEngine.mark(); Reset to saved status expertEngine.resetToMark(initialStatus);

19 Facts: Integration with Java
(import gov.sandia.jess.example.pricing.model.*) (deftemplate order (declare (from-class Order))) (definstance <template-name> <Java object> [static | dynamic | auto] ) Ex: (definstance order (new Order price)) (add <Java object>) (definstance <classname> <Java object> auto) (undefinstance (<java-object> | * ))

20 Java from Jess Source: awtdraw.clp (import java.awt.event.WindowEvent)
(import java.awt.event.WindowListener) (import java.awt.Frame) (import java.awt.Color) (deffunction create-components () (bind ?f (new Frame "Drawing Demo")) (?f addWindowListener (implement WindowListener using (lambda (?name?event) (if (eq ?name windowClosing) then (System.exit 0))))) (bind ?c (new jess.awt.Canvas painter (engine))) (?f add "Center" ?c) (?f setSize ) (?f setVisible TRUE))

21 Transferring values JESS-JAVA
Rete: public Value store(String name, Value val); public Value store(String name, Object val); public Value fetch(String name); JESS: (store <name> <value>) (fetch <name>)

22 Blood Groups Sample Loading persons from JAVA while keeping blood rules in JESS (deftemplate Person (declare (from-class Person)) ) private List<Person> getDonors(){ List<Person> donors = new ArrayList<Person>(); donors.add(new Person("John", "O")); donors.add(new Person("Stan", "O")); donors.add(new Person("Peter", "A")); donors.add(new Person("Bruce", "B")); donors.add(new Person("Dan", "AB")); donors.add(new Person("Mathew", "A")); donors.add(new Person("Andrew", "B")); return donors; } expertEngine.addAll(getDonors());

23 JESS Static knowledge ;person needing blood
(deftemplate need-transfusion (slot who) ) ;transfusion criteria (deftemplate blood-acceptance (slot acceptor) (multislot donators) ;static knowledge (deffacts acceptance-criteria (blood-acceptance (acceptor O) (donators O)) (blood-acceptance (acceptor A) (donators O A)) (blood-acceptance (acceptor B) (donators O A B)) (blood-acceptance (acceptor AB) (donators O A B AB))

24 JESS side elements (defrule transfusion =>
(need-transfusion (who ?who)) (Person (name ?who) (blood ?required)) (Person (name ?source&~?who) (blood ?bg)) (blood-acceptance (acceptor ?required) (donators $? ?bg $?)) => (assert (compatibility (who ?who) (with ?source))) ) (defquery search-by-name "Finds compatibilities for a given name" (declare (variables ?name)) (compatibility (who ?name) (with ?with))

25 JAVA side elements //create a person object and make it available in the expertise Person personNeedingBlood = new Person(name, bg); expertEngine.add(personNeedingBlood); //create the needed transfusion fact and assert it String factStr = "(need-transfusion (who \"" + name + "\"))"; expertEngine.assertString(factStr); //collect the result QueryResult result = expertEngine.runQueryStar("search-by-name", new ValueVector().add(new Value(name, RU.STRING))); while (result.next()) { System.out.println(name + " is compatible with: " + result.getString("with")); }

26 Blocks World Planning Transform goals in sub-goals
Think of robots manipulating objects Stacks of blocks Goal: move a block on top of another

27 Initial Data (block A) (block B) FLOOR ;defining a goal (deftemplate goal (slot move) (slot on-top-of) ) ;defining a move (deftemplate move (slot block) (slot support) ;defining the stacks (deftemplate on-top-of (slot upper) (slot lower)

28 Initial status (deffacts initial-status (block A) (block B) (block C) (block D) (block E) (block F) (block G) (on-top-of (lower A) (upper B)) (on-top-of (lower B) (upper C)) (on-top-of (lower D) (upper E)) (on-top-of (lower E) (upper F)) (on-top-of (lower C) (upper nothing)) (on-top-of (lower F) (upper nothing)) (on-top-of (lower G) (upper nothing)) (on-top-of (lower floor) (upper A)) (on-top-of (lower floor) (upper D)) (on-top-of (lower floor) (upper G)) (goal (move B) (on-top-of D)) )

29 Moving directly ;rule to directly move a block on top of another (defrule move-directly ?g <- (goal (move ?blockToMove) (on-top-of ?blockSupport)) (block ?blockToMove) (block ?blockSupport) (on-top-of (lower ?blockToMove) (upper nothing)) ?s1 <- (on-top-of (lower ?blockSupport) (upper nothing)) ?s2 <- (on-top-of (lower ?someBlock) (upper ?blockToMove)) => (retract ?g ?s1 ?s2) (assert (on-top-of (lower ?someBlock) (upper nothing))) (assert (on-top-of (lower ?blockSupport) (upper ?blockToMove))) (printout t "Moved " ?blockToMove " on " ?blockSupport crlf))

30 Moving to floor ;rule to move a block on the floor (defrule move-to-floor ?g <- (goal (move ?blockToMove) (on-top-of floor)) (block ?blockToMove) (on-top-of (lower ?blockToMove) (upper nothing)) ?s <- (on-top-of (lower ?someBlock) (upper ?blockToMove)) => (retract ?g ?s) (assert (on-top-of (lower ?someBlock) (upper nothing))) (assert (on-top-of (lower floor) (upper ?blockToMove))) (printout t "Moved " ?blockToMove " to floor” crlf) )

31 Creating sub-goals ;rule to free the moving block (defrule clear-upper (goal (move ?block)) (block ?block) (on-top-of (lower ?block) (upper ?someBlock)) (block ?someBlock) => (assert (goal (move ?someBlock) (on-top-of floor))) ) ;rule to free the support block (defrule clear-support (goal (on-top-of ?blockSupport)) (block ?blockSupport) (on-top-of (lower ?blockSupport) (upper ?someBlock))

32 Collecting the movements
Purpose: separating reasoning from acting New template: ;movements template (deftemplate moves (multislot movements) ) A function (deffunction moveBlock (?block ?support ?movementsFact) (bind ?newMove (assert (move (block ?block) (support ?support)))) (bind ?existingMoves (fact-slot-value ?movementsFact movements)) (modify ?movementsFact (movements ?existingMoves ?newMove))

33 Rule adjustments ;rule to directly move a block on top of another
(defrule move-directly ?g <- (goal (move ?blockToMove) (on-top-of ?blockSupport)) (block ?blockToMove) (block ?blockSupport) (on-top-of (lower ?blockToMove) (upper nothing)) ?s1 <- (on-top-of (lower ?blockSupport) (upper nothing)) ?s2 <- (on-top-of (lower ?someBlock) (upper ?blockToMove)) ?m <- (moves) => (retract ?g ?s1 ?s2) (assert (on-top-of (lower ?someBlock) (upper nothing))) (assert (on-top-of (lower ?blockSupport) (upper ?blockToMove))) (moveBlock ?blockToMove ?blockSupport ?m) ) Similar for move-to-floor

34 Using results (deffunction printMoves (?moves) (bind ?i 1) (while (<= ?i (length$ ?moves)) do (bind ?move (nth$ ?i ?moves)) (bind ?i (+ ?i 1)) (printout t "Moved " (fact-slot-value ?move block) " on " (fact-slot-value ?move support) crlf) ) (defrule finalPrint (declare (salience -10)) ?m <- (moves (movements $?moves)) => (printMoves $?moves)

35 Integrating Jess and Java
Purpose: managing movements from Java Install few plugins The Rete class: import jess.Rete; It is a rule engine with agenda, working memory and knowledge See docs at:

36 Improvements Collect movements for specific goals
Make the floor being able to support a limited number of stacks Create a GUI for showing stacks, specifying goals and reacting to changes


Download ppt "JESS-JAVA Integration"

Similar presentations


Ads by Google