JESS-JAVA Integration

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
The CLIPS Programming Tool History of CLIPS –Influenced by OPS5 and ART –Implemented in C for efficiency and portability –Developed by NASA, distributed.
Expert System Shells - Examples
Samad Paydar Ferdowsi University of Mashhad.  C Language Integrated Production System (CLIPS)  A tool for building expert systems  An expert system.
1 01/12/2011Knowledge-Based Systems, Paula Matuszek Intro to CLIPS Paula Matuszek CSC 9010, Spring, 2011.
Chapter 8 Pattern Matching
Introduction to CLIPS (Lecture Note #17)
JESS : Java Expert System Shell
Chapter 7: Introduction to CLIPS
CLIPS C Language Integrated Production System Note: Some slides and/or pictures are adapted from Lecture slides / Books of Dr Zafar Alvi.
Chapter 9 Subprogram Control Consider program as a tree- –Each parent calls (transfers control to) child –Parent resumes when child completes –Copy rule.
Introduction to CLIPS (Chapter 7) Fact List (contains data) Knowledge Base (contains rules) Inference Engine (controls execution)
1 Review of classes and subclasses M fast through this material, since by now all have seen it in CS100 or the Java bootcamp First packages Then classes.
Mary Lou Maher MIT Fall 2002 Jess: A Production System Language Agent-Based Virtual Worlds.
© C. Kemke Control 1 COMP 4200: Expert Systems Dr. Christel Kemke Department of Computer Science University of Manitoba.
Chapter 9: Modular Design, Execution Control, and Rule Efficiency Expert Systems: Principles and Programming, Fourth Edition.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
ISBN Lecture 01 Preliminaries. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Lecture 01 Topics Motivation Programming.
Introduction to Jess.
Jess Presentation by Chun Ping Wang. What is Jess? Jess is an expert system shell made for java. Rete pattern algorithm. Purpose. –Jess is best use for.
A. Frank - P. Weisberg Operating Systems Introduction to Cooperating Processes.
CS 561, Session 25 1 Introduction to CLIPS Overview of CLIPS Facts Rules Rule firing Control techniques Example.
Data Structures Data structures permit the storage of related data for use in your program. –Arrays.
Intro to Jess The Java Expert System Shell By Jason Morris Morris Technical Solutions.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Chapter 9: Modular Design, Execution Control, and Rule Efficiency Expert Systems: Principles and Programming, Fourth Edition.
Review Topics Test 1. Background Topics Definitions of Artificial Intelligence & Turing Test Physical symbol system hypothesis vs connectionist approaches.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 7: Introduction to CLIPS Expert Systems: Principles and Programming, Fourth Edition.
Jess: A Rule-Based Programming Environment Reporter: Yu Lun Kuo Date: April 10, 2006 Expert System.
Java Expert System Shell JESS 報告者 : 江梓安. Why we need an expert systems? Conventional programming languages Conventional programming languages Complex.
Chapter 7: Introduction to CLIPS Presented By: Farnaz Ronaghi.
Artificial Intelligence as Representation and Search.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Expert Systems Chapter 7 Introduction to CLIPS Entering and Exiting CLIPS A> CLIPS  CLIPS (V6.5 09/01/97) CLIPS> exit exit CLIPS> (+ 3 4)  7 CLIPS>
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
1 Knowledge Based Systems (CM0377) Lecture 10 (Last modified 19th March 2001)
Intro to Jess The Java Expert System Shell By Jason Morris Morris Technical Solutions.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Artificial Intelligence Lecture No. 19 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
Programming Languages and Paradigms Activation Records in Java.
Mostly adopted from Jason Morris notes (Morris Technical Solutions)
The CLIPS Expert System Shell Dr Nicholas Gibbins
Summary for final exam Agent System..
Business Rules Engine in Java Introduction to JBoss Rules by Tom Sausner.
Introduction to CLIPS 2 Session 13 Course: T0273 – EXPERT SYSTEMS Year: 2014.
Jörg Kewisch, June 10, 2013, LILUG Meeting CLIPS C Language Integrated Production System Developed at the Software Development Branch, NASA Lyndon B. Johnson.
Implementing Subprograms
Integration Part 2 Intelligent Systems Integration Part 2
VBA - Excel VBA is Visual Basic for Applications
Intelligent Systems JESS constructs.
Java Programming Language
Semantic Analysis with Emphasis on Name Analysis
LESSON 20.
Chapter 7: Introduction to CLIPS
JavaBeans and JSP CS-422.
Stacks Chapter 4.
Implementing Subprograms
Variables ICS2O.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
بسم الله الرحمن الرحیم آموزش نرم افزار CLIPS
Chapter 11: Classes, Instances, and Message-Handlers
Object Oriented Programming in java
JESS (Java Expert System Shall)
Jess Knowledge, Influence, Behavior
Chap 2. Identifiers, Keywords, and Types
SPL – PS1 Introduction to C++.
Implementing Subprograms
Presentation transcript:

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

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

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 http://www.jessrules.com/jess/docs/71/api/jess/Rete.html

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());

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

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()); }

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()); }

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);

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));

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)

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());

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?

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>))

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)

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);

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());

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")); } http://www.jessrules.com/jess/docs/71/queries.html

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);

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> | * ))

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 200 200) (?f setVisible TRUE))

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>)

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());

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))

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))

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")); }

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

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)

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)) )

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))

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) )

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))

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))

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

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)

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: http://www.jessrules.com/jess/docs/71/library.html

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