Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Jess The Java Expert System Shell

Similar presentations


Presentation on theme: "Intro to Jess The Java Expert System Shell"— Presentation transcript:

1 Intro to Jess The Java Expert System Shell
By Jason Morris Morris Technical Solutions

2 Quotable Quotes Each problem that I solved became a rule which served afterwards to solve other problems. - Rene Descartes

3 Quotable Quotes As a rule we disbelieve all the facts and theories for which we have no use. - William James

4 Quotable Quotes Hell, there are no rules here -- we're trying to accomplish something. - Thomas A. Edison

5 Quotable Quotes Get your facts first, and then you can distort them as much as you please. - Mark Twain

6 Quotable Quotes If the facts don't fit the theory, change the facts. - Albert Einstein

7 Quotable Quotes There are two rules for success:
1) Never tell everything you know. - Roger H. Lincoln

8 Quotable Quotes Facts do not cease to exist just because they are ignored. - Aldous Huxley

9 Agenda What are expert systems? What are rule-based expert systems?
Introduction to Jess The Jess Language 5 minute break We’ll just briefly define what expert systems are. Then we’ll introduce rule-based systems. Next, we’ll jump into Jess and talk about how it differs from other programming paradigms. While there, we’ll look at the Jess scripting language and the Jess API To tie it all together, we’ll examine a small expert system to assist with choosing an appropriate design pattern for a given application. Finally, we'll list some references and places where you can get more info.

10 Agenda Scripting & The Jess API Demo 1 : Design Pattern Expert
Demo 2 : Catalog Servlet References and Further Study Q & A In the two hours that I have blocked, I cannot possibly show you all of Jess. My aim is to pique your curiosity and hopefully give you some insight into a re-emerging field.

11 Expert Systems… Are a branch of artificial intelligence.
Simulate human reasoning in some domain. “Reason” by heuristic or approximate methods. Explain and justify solutions in user-friendly terms. A human expert must also explain how he/she arrived at a particular solution.

12 Types Of Expert Systems
Neural Networks Blackboard Systems Belief (Bayesian) Networks Case-Based Reasoning Rule-Based Systems Neural Nets are the quintessential expert system of science fiction fame – Hal 9000 for example. Non-structured data redundantly linked via multiple paths and massively parallel processed by multiple CPUs. The Blackboard metaphor is an interesting approach that models a collection of domain experts all trying to solve a complex problem. Each expert module tries to solve parts of the problem specific to its domain. Belief (Bayesian) Networks were originally researched as an approach to modeling natural language. Use a probabilistic approach to finding solutions. Case-Based Reasoning uses pattern-matching mimicking the way humans recall previously previous problem solutions. Derived solutions are based on similarity to an existing solution that best fits the problem parameters. Successful solutions are integrated into the case-base. Example would be chess masters who recall patterns of previous games and stratagems rather than calculate from first principles. Rule-Based Systems are the oldest and most researched form of expert system architecture. They simulate the reasoning that human experts use to arrive at conclusions by using first principles or “rules of thumb” called heuristics.

13 Rule-Based Expert Systems
Originated from AI research in the 70s and 80s. Problem data stored as facts. “Reason” using IF…THEN…ELSE rules. Can “reason” deductively (forward-chaining) or inductively (backward-chaining). The DENDRAL Project ( ) One of the earliest expert systems. DENDRAL began as an effort to explore the mechanization of scientific reasoning and the formalization of scientific knowledge by working within a specific domain of science, organic chemistry. Think of a fact as a “truth McNugget”. :-D

14 When to Use Rule-Based Systems
Problem Domain = narrow, well-understood domain theory Knowledge Representation = facts and rules Output = recommendation Explanation = rule firing trace Learning Ability = generally no (but…) Problem domain: one of the usage problems with rule based systems is that you have to “know” the solution to the problem beforehand. In other words, a finite collection of facts must result in a particular, reproducible solution. The problem has to be solvable by reasoning along axioms or principles. The problem space needs to be quantifiable in terms of facts and the domain knowledge must be quantifiable in terms of rules. The output is in the form of a terse or verbose recommendation, the explanation of which is typically a trace of all the rules that fired. Now, most rule systems don’t have the capacity to autonomously “learn” as it solves problems (i.e., neural nets, case-based system can do this…by adding nodes or cases.) However, rule-based systems that use a decision-tree metaphor can simulate “learning” by adding nodes to the decision network. A classic example is the animal guessing program. (demo)

15 Inference Process Rules and facts compared using pattern matcher.
Matched rules activated into a conflict set. Conflict set resolved into agenda (process called conflict resolution). Rule engine fires on agenda. Engine cycles until all rules are satisfied. The interesting thing is that rules can add, delete, or alter facts in the working memory. They can also call other code (Jess functions or Java methods) The rule engine fires only once on any given set of facts in working memory.

16 The Java Expert System Shell
Developed at Sandia National Laboratories in late 1990s. Created by Dr. Ernest J. Friedman-Hill. Inspired by the AI production rule language CLIPS. Fully developed Java API for creating rule-based expert systems. Jess came along when Java was very young! According to Dr. Friedman-Hill, Jess was nearly implemented in a hacked kind of C! CLIPS was developed by the Johnson Space Center at NASA in the early 80s. BTW - There is also an Object-Oriented version of CLIPS called COOL (CLIPS Object Oriented Language)

17 Rule-Based Expert System Architecture
Rule Base (knowledge base) Working Memory (fact base) Inference Engine (rule engine) This is the typical architecture common to rule-based systems.

18 Inference (Rule) Engines
Pattern Matcher – decides what rules to fire and when. Agenda – schedules the order in which activated rules will fire. Execution Engine – responsible for firing rules and executing other code. This mechanism underscores a key difference between procedural programming and declarative programming.

19 Inference Process Match the facts against the rules.
Choose which rules to fire. Execute the actions associated with the rules. We’ll have more to say when we get to the section on creating rules on exactly how Jess matches facts to rules.

20 How Does Jess Work? Jess matches facts in the fact base to rules in the rule base. The rules contain function calls that manipulate the fact base and/or other Java code. Jess uses the Rete (ree-tee) algorithm to match patterns. Rete network = an interconnected collection of nodes = working memory. So this is an overview of how Jess operates.

21 Jess Architecture Diagram
WORKING MEMORY INFERENCE ENGINE EXECUTION ENGINE PATTERN MATCHER RULE BASE Here you can see how all the parts fit together. AGENDA

22 Procedural Programming
Traditional programming (BASIC, C, FORTRAN, Pascal, etc.). Largely based on functions. Programmer controls logic. Sequential and deterministic. Object-oriented programming is procedural within object methods. Ohhh! Ordinarily, I practice cliché-free presenting, but here I’ll break my own rule and say that we are are entering a “paradigm shift” zone – that is to say that programming in rules is not that same as programming in other procedural or object-oriented languages.

23 Declarative Programming
New programming paradigm - rules. Programmer does not really control code logic. Rule engine finds most efficient “path” of code execution. Replaces hard to maintain nested IF…THEN…ELSE coding. New in the sense that it may be new to you… the paradigm actually goes back to the 1940s.

24 Wait a minute! What? I…I can’t control my code??
Well…yes and no…but don’t worry, Calvin!

25 Thought Experiment… Imagine writing a procedural/OOP algorithm to solve a jigsaw puzzle. 500+ pieces, different shapes and colors. Polymorphism runs amok! Yet we manage to solve the puzzle…

26 Intuition and Rules Dump the puzzle pieces on a card table in no particular order. Your brain instinctively begins to apply rules to solve the puzzle! What might this look like in code?

27 Intuitive Inferencing
(corner_found (piece_is_corner) => (assert corner-found) (save_piece)) Your brain “knows” what to do with a corner piece … (edge_found (piece_is_edge) => (assert edge-found) (save_piece)) … and an edge piece.

28 What’s Going On… Your brain recalls rules or heuristics to solve the problem. Your brain pattern-matches, prioritizes, and applies rules according to the facts in memory. A particular solution algorithm emerges as rules “fire” on facts.

29 The Jess Language Architecturally inspired by CLIPS LISP-like syntax.
Basic data structure is the list. Can be used to script Java API. Can be used to access JavaBeans. Easy to learn and use. Jess is not a copy or port of CLIPS… though it does model some of its features. LISP (Lost Inside Stupid Parentheses!) :-D Lists are untyped, unordered data structures similar to collections. Those of you program Java on your Emacs will instantly recognize the LISP-like syntax.

30 Your very first Jess program!
Obligatory Tradition Your very first Jess program! (printout t “Hello PJUG-ers!” crlf) The “t” is a parameter that directs to standard output. Q. What do you notice?? Any LISP folks here? :-D A. The whole statement is a list!

31 Lists in Jess Here are some valid lists in Jess:
(a b c) ; list of tokens (1 2 3) ; list of integers (+ 2 3) ; an expression (“Hello world!”) ; a string (foo ?x ?y) ; a function call Again the head of a list has a special connotation – Jess looks to see if it’s a function.

32 Jess Variables Named containers that hold a single value.
Untyped. Begin with a ? mark. Can change types during lifetime. Assigned using bind function. OK… I am referring to Jess “script” variables, obviously not anything inside Java code that uses the Jess API. This is not uncommon in scripting languages in view of the simplified syntax and coding it affords. For example, JavaScript variables are untyped as well.

33 Jess Variables and Lists
Everything is a list in Jess! EXAMPLE: Adding two numbers (bind ?x 2) ; assign x = 2 (bind ?y 3) ; assign y = 3 (bind ?result (+ ?x ?y)) ; find sum Like LISP, Jess expressions are evaluated from the inside out, passing their resulting values to the next level of nesting.

34 Control Flow Common Jess-specific foreach if/then/else while apply
build eval progn Apply – calls a function on a given set of arguments. Build – parses and executes a function from a string. Eval - parses and executes a function from a string. Progn – like an in-line function call…like an anonymous method in LISP.

35 Jess Functions Even functions are lists. (deffunction get-input()
“Get user input from console.” (bind ?s (read)) (return ?s)) Q. So how would you write a call to calculate the area of sphere 2 meters in radius? Pass a list to the Jess interpreter containing the function name at the head of the list and then the expected parameters. So given a function like (deffunction area-sphere (?radius) “Calculate the area of a sphere” (bind ?area (* (* (pi) 2) (* ?radius ?radius))) (return ?area)) We could ask Jess to print out: (printout t "The surface area of a radius = 2 meter sphere is " + (area-sphere 1) + " m^2")

36 Jess Function Example (deffunction area-sphere (?radius)
“Calculate the area of a sphere” (bind ?area (* (* (pi) 2)(* ?radius ?radius))) (return ?area))

37 Jess Function Example How do we use this in Jess?
(printout t "The surface area of a radius = 2 meter sphere is " + (area-sphere 2) + " m^2")

38 Working With Facts Facts have a head and one or more slots.
Slots hold data (can be typed). Multislots can hold lists. You can modify slot values at runtime. Facts are constructed from templates. 1. We’ll take a look at some facts in the next slides. 2. You can explicitly specify the type of data in a slot when you define the fact in a template. 3. The multislot can appear anywhere in the list of slots in a fact. 4. Facts are like physical objects in the system. Rules are like actions to be performed.

39 Jess Fact Types Ordered – head only. Ordered – single slot.
Unordered – multiple slot, like a database record. Shadow – slots correspond to properties of a JavaBean. I promise not to make some lame “just the facts” joke. :-D That’s a subreference to the old show Dragnet for you younger programmers.

40 Deftemplate Used to define the structure of a fact. (deftemplate
pattern “A design pattern.” (slot name) (slot type (default “creation”)) (slot intent) (slot solution)) Facts can be asserted with slots in any order. Omitted slots use default values. Unspecified default values are null.

41 Asserting Facts Facts store the initial conditions.
;; Asserting a new “pattern” fact. (printout t “Enter pattern name:” crlf) (bind ?x getInput) (assert pattern (name ?x)) Recall the getInput function that we wrote a few slides back… that read a line of input from the console. The Jess command Assert adds a fact to working memory.

42 All Kinds of Facts ;; An ordered fact with no slots – a placeholder that indicates state. (assert(answer-is-valid)) ;; A ordered fact of one slot (assert(weightfactor 0.75)) The ordered fact with no slots is like a “truth-McNugget”, a “trigger” that sets off other rules by indicating a change in state of the problem space. This is the most common usage of ordered facts. The ordered fact with a single value is like problem parameter that other rules can use later… imagine a predicate constraint that says: (defrule check-valid-weight ?wf <- (weightfactor ?f) (answer ?x&: (<= 0.5 (* ?f ?x))) => (assert ((answeris-valid)) As long as there is no conflict with any fact template, you can assert facts without the assert function. Consider: Q. How would you use the (answer-is-valid) fact? A. You would write a rule that looks for the presence of a (answer-is-valid) fact in working memory, then takes some action if it finds one.

43 Shadow Facts Shadow facts are unordered facts whose slots correspond to the properties of a JavaBean. defclass – creates a deftemplate from a bean. definstance – adds bean to working memory. UPSHOT: Jess lets you put Java objects into working memory as long as follow the JavaBean spec. Shadow facts connect Jess’ working memory to the application containing the Jess engine. Remember that Jess really shines as a component technology in a greater Java application.

44 Jess Rules… … are the knowledge-base of the system.
… fire only once on a given set of facts. … use pattern constraints to match facts. … are much faster than IF-THEN statements. Rules really are the repository of the knowledge elicited from the human expert emulated by the expert system. Think about the second item here…what does that imply? Faster in the sense that the Rete algorithm optimizes the order in which the rules are fired.

45 Rule Syntax Rules have a “left-hand” side (LHS) and a “right-hand” side (RHS). The LHS contains facts fitting certain patterns. The RHS contains function calls.

46 Simple Rule Example Checking working memory state.
;; A not very useful error handler (defrule report-error (error-is-present) => (printout t “There is an error” crlf)) Q. Ok… now what does this mean? If I told you that the symbol “=>” is read as “THEN”, can you discern the meaning of the rule? A. The rule looks in working memory for the presence of a fact of type (error-is-present) [BTW – what kind of fact is this?] (ordered with no slots) THEN if that fact is in working memory, Jess prints a statement to the console stating that fact.

47 A More Complex Rule Using pattern bindings in rules.
;; A more useful error handler (defrule report-err ?err <- (is-error (msg ?msg)) => (printout t "Error was: " ?msg crlf) (retract ?err)) This illustrates some interesting Jess abilities… Q. Can you guess at what the code above the => does? A. It looks for a fact of type is-error with any msg slot. The cool thing is that the variable ?msg is now available on the RHS of the rule! A reference to the matched fact object is stored in ?err. The RHS can use that “pointer” to modify, retract, or duplicate that fact.

48 More Pattern and Control Tools
matching control and structure Literal / variable constraints Logical conditional tests Predicate functions Salience Modules Defquery Backward-chaining

49 Break Time! Let’s take a quick 5 minute pause…

50 Scripting Java from Jess
You can interactively access all Java APIs from Jess. This makes exploring Java somewhat easier and immediate. No code, compile, debug cycle.

51 Scripting Java with Jess
(import javax.swing.*) (import java.awt.*) (import java.awt.event.*) (set-reset-globals FALSE) (defglobal ?*frame* = (new JFrame "Hello PJUG")) (defglobal ?*button* = (new JButton "Click my PJUG")) (?*frame* setSize ) ((?*frame* getContentPane) add ?*button*) (?*frame* setVisible TRUE) swingDemo.bat

52 Demo 1: PAT (Pattern Analysis Tool)
PAT is a simple decision-tree for choosing a Java design-pattern. Uses an initial interview to establish problem space. Recommends a GoF Java design-pattern to fit the available facts. examples/pattern.clp

53 The Jess API Organized into 3 packages, 64 classes (not hard to learn)
jess - inference engine “guts”. jess.awt – GUI wrappers. jess.factory - Allows extensions that “get into the guts of Jess”.

54 The Rete (ree-tee) Object
The reasoning engine and the central class in the Jess library. Executes the built Rete network, and coordinates many other activities. Rete is essentially a facade for the Jess API.

55 Using the Jess API… try { Rete engine = new Rete(); engine.executeCommand( “printout t “Hello PJUG”); engine.run(); } catch (JessException je {} …is simple…all you really do need to do is call one or more Rete methods …

56 Demo 2: Catalog Servlet import jess.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public abstract class BaseServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }... Here is an example of a Jess application running as a Java servlet…

57 Pattern References Shalloway, A., Design Patterns Explained, Addison-Wesley, 2002 Gamma, E. et. al., Design Patterns: Elements of Reusable Object-Orient Software, Addison-Wesley, 1995

58 Expert Systems References
Friedman-Hill, E. J., Jess In Action, Manning Press, 2003 Jackson, P., Introduction to Expert Systems – 3rd Ed., Addison-Wesley, 1999 Giarratano, J., Expert Systems: Principals and Programming, PSW-Kent, 1989

59 Links Download Jess at: Join the Jess user community at:
Join the Jess user community at: See Dr. Friedman-Hill’s Jess in Action at: Downloading Jess is straight forward. Closely follow the instructions on installing it as there are some sticky points. Then, it’s just a simple matter of adding the jess package (jess.jar) to any Java project that you want to code. FYI - Though Dr. Friedman-Hill is very cordial and generous about helping newbies with FAQs, he can be understandably a little terse with those who do not employ the “RTFD” approach to resolving questions prior to spamming the Jess newsgroup. For those of you not familiar with this method… see me after the presentation and I’ll be happy to expand the acronym in private. :-D If you’re going to program in Jess, you will definitely need a copy of Jess in Action – mine is dog-eared already!

60 For Further Study CLIPS Expert System Shell
FuzzyJ Website IR_public/fuzzy/ fuzzyJToolkit2.html CLIPS is the original expert system shell that formed the inspiration for Jess. Again, it is not a wrapper around CLIPS, but borrows many of its ideas. Jess uses a customized Rete inference engine that is different than the one in CLIPS, but Jess can run most CLIPS files. Learning some CLIPS will help in learning Jess, but the converse is not necessarily true. FuzzyJ is a fuzzy logic extension to Jess written by Bob Orchard at the National Research Council of Canada at You can download all his stuff here after you’ve mastered the Jess basics and then some… Jess In Action does feature a chapter by Orchard on a fuzzy Jess HVAC control system.

61 Q & A Thanks for your attention, and I hope that you try Jess!


Download ppt "Intro to Jess The Java Expert System Shell"

Similar presentations


Ads by Google