Wednesday, March 4, 2009

Embedding Jess in Java for Agent Models

I am working with the reasoning mechanism for my agent models and decided to use the backward and forward chaining methods found in Jess at http://www.jessrules.com/ . I can embed Jess in Java with the following code once I add the jess.jar to the library in an IDE like Eclipse and ran the code below shown in Figure 1.


Figure 1. Java and Jess in Eclipse


import jess.Deffacts;
import jess.Fact;
import jess.JessException;
import jess.RU;
import jess.Rete;
import jess.Value;
/*
public class testJess {
/*

public static void main(String[] args) throws JessException {

String buff;
/*define instance for jess interface class*/
Rete engine = new Rete();
engine.batch("testFacts.clp");
engine.reset();
buff = "(facts)";
engine.eval(buff);
buff = "(assert (birthday Jeff))";
engine.eval(buff);/* execute it */
buff = "(facts)";
engine.eval(buff);
engine.run();
System.out.println("Happy Birthday");
buff = "(facts)";
engine.eval(buff);
/* define new fact (template using API*/
engine.eval("(deftemplate point (slot x) (slot y))");
Fact f = new Fact("point", engine);
f.setSlotValue("x", new Value(37, RU.INTEGER));
f.setSlotValue("y", new Value(49, RU.INTEGER));
engine.assertFact(f);
buff = "(facts)";
engine.eval(buff);
}
}

The working memory of Jess has three parts which contains the deftemplate that defines the different kinds of facts contained in the deffacts. Defrule defines the rules to operate on the facts. This is my testfile-testFacts.clp:

(printout t "First Jess in Java" crlf)
(deftemplate personal-data
(slot name)
(slot age)
(slot weight)
(slot height)
(multislot blood-pressure)
)


(deffacts people
(personal-data (name Jeff) (age 48) (weight 220)
(height 200) (blood-pressure 130 80))
(personal-data (name David) (age 20) (weight 170)
(height 100) (blood-pressure 200 40)))


(defrule birthday
?birthday <- (birthday ?name) ?data-fact <- (personal-data (name ?name) (age ?age)) =>
(modify ?data-fact (age (+ ?age 1)))
(retract ?birthday)
)

Using this example, one can build text files of templates, facts and rules to read by the Rete engine in Java. Other examples like Jess are open source rule engines such as

  • Drools
  • Hannurapi Rules
  • JEOPS
  • JRuleEngine
  • Mandarax
  • Open Lexicon
  • Prova
  • SweetRules
  • Take
  • Termware
  • Zionis

For more information, check out http://www.businessreviewonline.com/os/archives/2008/07/10_best_open_so.html . One example that uses the Rete engine is Drools at http://www.jboss.org/drools/ . More on this in the next post.

References

Friedman-Hill, E. (2003). Jess In Action: Rule Based Systems in Java. Greenwich, CT: Manning Publications.

No comments: