Category: Drools



Hi,
This is a short screencast that I have recorded to explain in a few minutes some of the features and concepts related to Drools Expert. Inside this screencast you will find a simple example that it will help you to understand some of the basics of an Expert System.
Please click the image to watch the screencast…

I hope it helps :) .

Short Approach…

It’s an excellent idea to combine 2 two technologies such as Drools and GWT to build Intelligent Web Applications. But there is a little bit of a problem at the moment to integrate them. Because Drools and GWT include the org.eclipse.jdt classes but with different JDT version. And when you run your application (mvn gwt:run) you will have an error like this:

Unable to parse module: com.google.gwt.user.User
java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.CompilationResult.getErrors()
[Lorg/eclipse/jdt/core/compiler/IProblem;
at com.google.gwt.dev.jdt.AbstractCompiler$ICompilerRequestorImpl.
acceptResult(AbstractCompiler.java:213)
at org.eclipse.jdt.internal.compiler.Compiler.compile
(Compiler.java:417)
...

Solution…

So to solve this problem you need to add an exclusion to your dependecy (that has the Drools-Core dependency) added in your Maven Gwt Application pom.xml. The exclusion in your pom should look like this:

<dependencies>
    [...]
<dependency>
           <groupId>com.wordpress.nicozan</groupId>
           <artifactId>dependency-with-drools-core</artifactId>
           <version>1.0</version>
           <exclusions>
                   <exclusion>
                           <groupId>org.eclipse.jdt.core.compiler</groupId>
                           <artifactId>ecj</artifactId>
                   </exclusion>
           </exclusions>
</dependency>
    [...]
</dependencies>

Short but helpful ;)

Introduction

As you might remember in previous posts I have talked about Knowledge Engineering, Expert Systems and Rule Based Systems. Today I’ll get back to those concepts and explain you the Protocol Analysis Method to do Knowledge Elicitation.

Protocol Analysis

Before we begin, I would like to highlight that there are other methods to elicit knowledge such as interviews, questionnaires and repertory grids.
This method have several steps, obviously lets start we the first one :

1- The Idea is to search and capture ,and then study, everything the expert says while he is solving a problem. That’s why we record the experts explanation with a tape recorder during his task. In other words, the expert have to explain what he is thinking.

2- After we record our experts explanation (Protocol),we have to write down the recorded audio and divide the text into segments. Please have a look at the next simple example:
Protocol: “As we can see the Porsche 911 is a very comfortable and fast car, so it is expensive”
Transcription:

Line

Text

1

As we can see

2

the Porsche 911

3

is a very comfortable

4

and fast car

5

so it is

6 expensive

In the example protocol,  the expert was explaining what makes a car expensive, thats this ob

3- Now it’s time to identify concepts, characteristics, values, relations and operators. Considering the Drools Expert tool: Concepts are facts, characteristics are the facts properties and values are the values of the properties.
The operators are elements use by the expert to move from a state of the problem to an other state closer to the final solution.
Let’s see the next classification table:

Element

ID

As we can see

Relation

Porsche 911

Concept
very comfortable

Value

fast

Value

so it is

Operator

expensive

Concept

The states in our problem can be Concepts or Characteristics, but not both at the same time. In this case I’ll choose Concepts as states of the problem.
In the table that follows we’ll specify the explicit relations:

Concepts

Characteristics Values
Porsche 911 (Comfort)

very comfortable

(Speed)

fast

Expensive

A value must be always related to a characteristic. If there is an explicit value in the text but there isn’t the explicit characteristic, we have to write the implicit one between parenthesis like the example above.
Now we represent the implicit relations, that are always between concepts.

After this schema, we draw, what is called,  a “Search Identification”:

4- Now that we have done our search identification it is time to write the rule associated to it. Obviously we’ll be using the DRL syntax of Drools Expert.

rule "It's an expensive car"
when
  $porsche : Porsche911( speed  == "Fast", comfort == “Very Comfortable” )
then
  System.out.println( “Car: ”  + $porsche.getName() + “ is an expensive car” );
end

Well, this short explanation would be enough for you to start your first knowledge elicitation and get closer to the knowledge engineering.

Drools-Guvnor – Spring Context Feature

Introduction

Drools-Guvnor has now the possibility to create, modify and delete Spring Context Files. This new feature allows you to define Drools Knowledge Bases, Knowledge Sessions, Knowledge Agents and Common Spring Beans inside your Spring Context File.

How to Create a Spring Context in Guvnor

You have to go to the Knowledge Bases Tag on the Left Menu and select:
Create New —> New Spring Context.
Like any other asset you will have to give it a name and set in which package it’ll be saved.

It is time to Edit our Spring Context

The next image shows the SpringContext Editor. You will be able to insert new tags in this XML file, by positioning your text cursor in the place where you would like to insert this new tag and then click on one of the options on the left palette. (KSession, KBase, Node, KAgent, Spring Bean)

Another feature of the SpringContext editor is that we can validate our XSD file against the XSD file implicitly referred in the Spring Context File. All you have to do is go to : Source—> Validate.

Adding New Buttons to our Palette

If you want to add new buttons to your palette, Drools Guvnor allows you to do this through a Properties File. The name of the file is springContextElements.properties, it’s located in the path:$GUVNOR_HOME/WEB-INF/Clases/springContextElements.properties.

Downloading The Spring Context Files

Each spring context is exposed through an URL. These URLs could be found at the bottom part of the Package editor where the context files are defined.

Stay tuned for updates related to Drools… ;) , this new feature is now in the trunk, in Drools 5.2.0.M1. :)

Well, we have reach the part number four of these posts related with Expert Systems. In this post we’ll be seeing the concept of INFERECE and some METHODS OF INFERENCE.


INTRODUCTION

In the knowledge domain that it knows about, the expert system “reasons” or makes inferences in the same way a human expert would infer the solution of a problem. That is, given some facts, a conclusion that follows is inferred.

For example, if your spouse hasn’t spoken to you in months, you may infer that he or she had nothing worthwhile to say. However, this is only one of several possible inferences.

In a rule-based system, the inference engine determines which rule antecedents, if any, are satisfied by the facts. Two general methods of inferencing are commonly used as the problem-solving strategies of expert systems: forward chaining and backward chaining.


INFERENCE

Is the standard technique by which expert systems solve problems. Expert Systems are commonly used when an inadequate algorithm or no algorithmic solution exists and inference offers the only possibility of a solution.

Decision structures, like binary trees, can be mechanically translated into production rules. This can be easily be done by a breath-first searching of the structure and by generating IF…THEN rules at every node. The breath-first search begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds a terminal node.


TYPES OF INFERENCE

There are many types: deduction, induction, intuition, heuristics, generate and test, abduction, default, auto-epistemic, nonmonotonic and analogy. The Commonsense knowledge could be a combination of any of these types. One of the most frequently used methods of drawing inferences is deductive logic, which has been used since ancient times to determine the validity of an argument. The meaning of argument in logic is a group of statements in which the last is claimed to be justified on the basis of the previous ones in the chain of reasoning.

Before we continue, we need to define one important term: Syllogism. Is a kind of logical argument in which one proposition (the conclusion) is inferred from two others (the premises) of a certain form.

Although Venn diagrams are a decision for syllogisms , the diagrams are inconvenient for more complex arguments because they become more difficult to read. Propositional Logic offers another means of describing arguments. In fact, we often use propositional logic without realizing it.
For example: If there is water and gas, I can cook the pasta. This argument can be expressed in a formal way by using letters to represent the proposition as follows:
A= There is water.
B= There is gas.
C= I can cook the pasta.

A ^ B —> C

The representation above, it might look familiar to you. Because it’s a representation of knowledge using production rules, like we explained in a previous post.


METHODS OF INFERENCE

Chain: a group of multiple inferences that connects a problem with its solution.
Forward Chain : a chain that is searched or traversed from a problem to its solution. Another way to describe it is, reasoning from facts to the conclusions that follow from facts.
Backward Chain: a chain that is traversed from a hypothesis back to the facts that support the hypothesis.

Some Characteristics of Forward and Backward Chaining:

FORDWARD CHAINING BACKWARD CHAINING
Planning, monitoring , control Diagnosis
Present to future Present to past
Antecedent to consequent Consequent to antecedent
Data driven, bottom up reasoning. Goal driven, top-down reasoning
Work forward to find what solutions follow from the facts. Work backward to find facts that support the hypothesis.
Breath-first search facilitated Depth-first search facilitated
Antecedents determine search Consequents determine search
Explanation not facilitated Explanation facilitated (Very Important in Exp Systems)


CONCLUSIONS

-Term inferencing is generally used for mechanical systems such as expert systems. Reasoning is for human thinking.
-The result of the inference depends on the knowledge base (rules) and the information we obtain from the real world (facts).
-The inferencing doesn’t pass rule by rule sequentially, like an algorithm that has a sequence of steps to reach an objective.

At the moment we decide to start building an Expert System, there are many elements to take into consideration. But in this new post we’ll take special attention to the interaction between the Human Expert, the Knowledge Engineer and the Knowledge Base of the Expert System.


INTRODUCTION

The expert’s knowledge about solving specific problems is called knowledge domain of the expert.
For example,a medical expert system designed to diagnose infectious diseases will have a great deal of knowledge about certain symptoms caused by infectious diseases. In this case, the deal of knowledge domain is medicine and consists on knowledge about diseases, symptoms, and treatments.
The next schema shows the relationship between the problem and the knowledge domain:


HUMAN EXPERT, KNOWLEDGE ENGINEER AND THE KNOWLEDGE

A Human Expert, as we defined in the previous post, is a person who has expertise in a certain area, this expert can solve problems that most people cannot solve or can solve them much more efficiently. The role of the Knowledge Engineer is to “translate” and filter all the information of the human expert, and put all the obtained knowledge in to the Knowledge Base (represented by rules commonly).
The next schema shows the process of how to build the knowledge base in an expert system:


CONCLUSIONS

-If the human expert can’t explain how a problem is solved, it’s not possible to encode the knowledge in an expert system based on explicit knowledge.
-A human expert has expertise in a certain area, not necessarily an expert in biology is going to be an expert in cooking pizza.
-The Knowledge Engineer usually doesn’t know technical terms of the expert, so the human expert should express his knowledge using simple and understandable terms.
-Expert systems increase confidence that the correct decision was made by providing a second opinion to a human expert or break a tie in case of disagreements by multiple human experts (An expert System can’t feel stress or be tired as a human expert).

In this post we’ll be discussing the Representation of Knowledge. There are many ways to represent knowledge, but we’ll see that the most common and useful representation is the Production Rules Representation.


INTRODUCTION

The study of knowledge is epistemology. There are two special types of knowledge, called a priori and a posteriori. The term a priori comes from the Latin and means “that which precedes”. A priori knowledge comes before and is independent of knowledge from the senses. As an example, the statement “everything that has a beginning has an end” is an example of a priori knowledge. A priori knowledge is considered to be universally true and cannot be denied without a contradiction. Logic statements and mathematical laws are examples of a priori knowledge.
The other type of knowledge is the a posteriori knowledge. The truth or falsity of a posteriori knowledge can be verified using senses experience, as in the statement “is raining”. However because sensory experience may not always be reliable, a posteriori knowledge can be denied on the basis of a new knowledge without the necessity of contradictions.


CLASSIFICATION OF KNOWLEDGE

Procedural Knowledge: is often referred to as knowing how to do something (i.e. knowing how to build a wall of bricks).
Declarative Knowledge: refers to knowing that something is true or false (i.e. Don’t use regular glue to attach the bricks)
Tacit Knowledge: is sometimes called unconscious knowledge because it cannot be expressed by language. (i.e. How to move any part of your body)


HIERARCHY OF KNOWLEDGE

The knowledge is part of a hierarchy, represented by the next pyramid:


  • NOISE: Items that are of little interest.

  • DATA: Items of potential interest.

  • INFORMATION: Processed data that are of interest.

  • KNOWLEDGE: Very specialized information.

  • META-KNOWLEDGE: Is knowledge about knowledge and expertise.

As we can see in the META-KNOWLEDGE definition, appears the term EXPERTISE. Although it is not explicitly define, expertise is specialized type of knowledge that experts have. Expertise it is not found in public information sources such as books and papers. Expertise is an implicit knowledge of an expert that must be extracted and made explicit so it can be encoded in an expert system.


PRODUCTIONS

There are different knowledge representation techniques: rules, semantic nets, frames, scripts, knowledge-representations languages, conceptual graphs, and others.
Production rules are commonly used as the knowledge base in expert systems. Normally one form for defining productions is the BNF (Backus-Naur Form or Backus Normal Form). This notation is a metalanguage for defining the syntax of language.


EXAMPLE

Let’s imagine that we own an Italian restaurant, and we have recently hired an expert cook. When he started to talk about his work in previous restaurants, we realized that we could stablished a set of rules based on his expertise. These rules are the next ones:

RULE1
If I am not paying attention to the pot with water, the pasta is going to be ruined.
PRODUCTION: I am not paying attention to the pot with water —> the pasta is ruined.

RULE2
If I am paying attention and the pot fulfilled with good pasta, good water and good sat, the pasta is correctly cooked.
PRODUCTION:
A = I am paying attention.
B = The pot is fulfilled with good pasta.
C = The pot is fulfilled with good water.
D = The pot is fulfilled with good salt.
E = The pasta is correctly cooked.

A ^ B ^ C ^ D —> E

RULE3
If the pasta is only made with 100% Durum Semolina and it’s imported from Italy, it’s a good pasta
PRODUCTION:
A = The pasta is only made with 100% Durum Semolina.
B = The pasta is imported from Italy.
C = It’s a good pasta.

A ^ B —> C

RULE4
If the salt is added when the water is ebullient, throw the pasta in the pot.
PRODUCTION: The salt is added when the water is ebullient —> throw the pasta in the pot.

RULE5
If pasta is al dente, the pasta is cooked.
PRODUCTION: The pasta is al dente —> the pasta is cooked.

RULE6
If the pasta is cooked, sauce the pasta.
PRODUCTION: The pasta is cooked —> sauce the pasta.


CONCLUSIONS

- The most common way to represent knowledge in Expert Systems is by using Production Rules.
- The Knowledge Base in an Expert System is fulfilled with the Expertise of a Human Expert (person who has expertise in a certain area)
- Facts can either mean DATA or INFORMATION.

Sometimes it’s necessary to enrich your knowledge before you start working with a new tool. This is because there are many important concepts that make the magic happen in your tool, and if you are developing or debugging you need to understand some theory to do the things correctly.


INTRODUCTION


Expert Systems is one of the many areas of AI (Artificial Intelligence). One Definition of Expert Systems is:
“An intelligent computer program that uses knowledge and inference procedures to solve problems that are difficult enough to require significant human expertise for their solutions” (Feigenbaun)

The next figure shows the Basic concept of an Expert System:

The user supplies facts to the expert system and receives expert advice in response. Internally, the expert system consists of two main components. The knowledge base contains knowedge with which the inference engine draws conclusions. These conclusions are expert system’s responses to the user’s queries for expertise.

The expert-system paradigm allows two levels of abstraction: data abstraction and knowledge abstraction. Expert System languages specifically separate the data from the methods of manipulating the data. And example of this, is the separation between facts (data abstraction) and rules (knowledge abstraction) in a rule-based expert system language. Drools Expert is a tool with these mentioned features.


ROOTS OF THE EXPERT SYSTEMS


Before we continue digging deeper into expert systems, it’s good idea to understand the origin of it. The roots of expert systems lie mainly in the area of human information processing, called Cognitive Science. Cognition is the study of how people think, specially solving problems. If you want to emulate human experts, you need to take into consideration the study of cognition.
Studies results have demonstrated that much of human problem solving or cognition could be expressed by IF…THEN-type production rules (antecedent—>consecuent). A rule corresponds to a small, modular collection of knowledge called chunk(fragment). Chunks are organized in a loose arrangement, with links to related chunks of knowledge. One theory is that all human memory is organized in chunks.


HOW THE BRAIN WORKS


The basic idea is that sensory input provides stimuli to the brain. The stimuli triggers the appropriate rules of long-term memory. One theory proposes that short-term memory represents the number of chunks that can be simultaneously active and considers human problem solving as a spreading of these activated chunks in the mind. The other element necessary for the human problem solving is a cognitive processor. The cognitive processor tries to finde the rules that will be activated by the appropriate stimuli. Only a rule that matched the stimulit would be activated.. If multiple rules are activated at one time, the cognitive processor must perform a conflict resolution to decide which rule has the highest priority.


CONCLUSIONS



  • The inference engine of modern expert systems corresponds to the cognitive processor.

  • The rules are allocated in the long-term memory, in analogy with the human problem solving model

  • The facts are allocated in the short-term memory, in analogy with the human problem solving model

Drools Fusion – Sliding Windows

Drools Fusion offers the Sliding Window operation, It gives us the posibilty to catch events of interest as the ones belonging to a window that is constantly moving. Drools Fusion has two Sliding Window implementations:

º Time Based Sliding Window: allows the user to write rules that will only match events occurring in the last X time units. The following code snippet shows the syntax of the operator:


rule “Sales that occurred in the last 10 minutes”
when
Sale() over window:time( 10m )
then
System.out.println(“A Sale occurred in the last 10 minutes”);
end

In the rule example above , the Sale() event will match IF AND ONLY IF it happens in the last 10 minutes.This 10 minutes are considered since the last event that is inserted into the working memory. So the Time Window is MOVED everytime we insert a new event.

º Length Based Sliding Window: works the same way as Time Based Window, but discard events based on the arrival of new events instead of flow of time.The following code snippet shows the syntax of the operator:


rule “Sales that had the article CoffeeCup from the last 10 Sales”
when
Sale(article == “CoffeCup”) over window:length( 10 )
then
System.out.println(“CoffeeCup Sold!”);
end

In the rule example above, the Sale() event will match IF AND ONLY IF the sale is one of the last 10 inserted sales into the working memory and its attribute article equal “CoffeCup”.

Some Considerations:
1. The Sliding Window is only available when engine is running in STREAM MODE.
2. Don`t forget to declare your EVENTS in the declaration part of your DRL File.

Drools Fusion – TimeStamp Tips

In this short post I`ll give you some tips to manage TimeStamps in Drools Fusion. You will probably use for timestamps, Date Objects or Long Types. The recommendation of this post is to use Long Types to represent timestamps.

If you are already using in your Drools Fusion implementation Date Objects, we recommend you to use the getTime() method that returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Inside your DRL File you should declare the timestamp attribute, If it`s typed as Date in your Event Class, as follows:


declare Event
@role(event)
@timestamp(timestamp.getTime())
end


Continuing with the tips, you should avoid instantiating the Date Object using the Date Constructor with parameters, except the one that receives a long type parameter representing the milliseconds since January 1, 1970, 00:00:00 GMT.

TESTING TIME…
When you are implementing Drools Fusion and it`s the time to do some testing, the best thing you can do is use the PseudoClock implementation for the Session Clock, by configuring your StatefulKnowledgeSession with the “pseudo” option :

….
//Pseudo Clock Configuration
KnowledgeSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
conf.setOption( ClockTypeOption.get( “pseudo” ) );

//StatefulKnowledgeSession : Once we have our KnowledgeBase we create a Session to use it.
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(conf,null);
SessionPseudoClock clock = ksession.getSessionClock();
….

Follow

Get every new post delivered to your Inbox.