Experta Tutorial
Experta Tutorial
Experta Tutorial
Release unknown
2 Examples 5
3 User Guide 7
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.1 Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.3 Difference between CLIPS and Experta . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2.1 From PyPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2.2 Getting the source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3.1 Facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3.2 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3.3 DefFacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3.4 KnowledgeEngine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4 Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.4.1 Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.4.2 Conditional Elements: Composing Patterns Together . . . . . . . . . . . . . . . . . . . . . 17
3.4.3 Field Constraints: FC for sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4.4 Composing FCs: &, | and ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4.5 Variable Binding: The << Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.4.6 MATCH object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.4.7 AS object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.4.8 Nested matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.4.9 Mutable objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.5 Cookbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4 API Documentation 25
4.1 Modules documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.1 experta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.2 experta.abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.3 experta.activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.4 experta.agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.5 experta.conditionalelement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.6 experta.engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
i
4.1.7 experta.factlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.8 experta.fact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.9 experta.fieldconstraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.10 experta.rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.11 experta.strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.12 experta.watchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.13 experta.matchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.14 experta.matchers.rete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.15 experta.matchers.rete.abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.16 experta.matchers.rete.check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.17 experta.matchers.rete.dnf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.18 experta.matchers.rete.mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.19 experta.matchers.rete.nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.20 experta.matchers.rete.token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.21 experta.matchers.rete.utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.1.22 experta.operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5 Release History 27
6 CHANGELOG 29
6.1 1.9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.2 1.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.3 1.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.4 1.9.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.5 1.8.0-1.8.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.6 1.7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.7 1.6.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.8 1.5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.9 1.4.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.10 1.3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.11 1.2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.12 1.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.13 1.1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.14 1.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.15 1.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.16 <1.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
7 Source documentation 33
ii
experta Documentation, Release unknown
Experta is a Python library for building expert systems strongly inspired by CLIPS.
class Light(Fact):
"""Info about the traffic light."""
pass
class RobotCrossStreet(KnowledgeEngine):
@Rule(Light(color='green'))
def green_light(self):
print("Walk")
@Rule(Light(color='red'))
def red_light(self):
print("Don't walk")
Contents 1
experta Documentation, Release unknown
2 Contents
CHAPTER 1
Experta is a Pyknow fork. Just replace any pyknow references in your code/examples to experta and everything should
work the same.
3
experta Documentation, Release unknown
Examples
5
experta Documentation, Release unknown
6 Chapter 2. Examples
CHAPTER 3
User Guide
3.1 Introduction
3.1.1 Philosophy
We aim to implement a Python alternative to CLIPS, as compatible as possible. With the goal of making it easy for
the CLIPS programmer to transfer all of his/her knowledge to this platform.
3.1.2 Features
• Python 3 compatible.
• Pure Python implementation.
• Matcher based on the RETE algorithm.
1. CLIPS is a programming language, Experta is a Python library. This imposes some limitations on the construc-
tions we can do (specially on the LHS of a rule).
2. CLIPS is written in C, Experta in Python. A noticeable impact in performance is to be expected.
3. In CLIPS you add facts using assert, in Python assert is a keyword, so we use declare instead.
3.2 Installation
7
experta Documentation, Release unknown
An expert system is a program capable of pairing up a set of facts with a set of rules to those facts, and execute some
actions based on the matching rules.
3.3.1 Facts
Facts are the basic unit of information of Experta. They are used by the system to reason about the problem.
Let’s enumerate some facts about Facts, so. . . metafacts ;)
1. The class Fact is a subclass of dict.
>>> f = Fact(a=1, b=2)
>>> f['a']
1
3. In contrast to dict, you can create a Fact without keys (only values), and Fact will create a numeric index for
your values.
>>> f = Fact('x', 'y', 'z')
>>> f[0]
'x'
4. You can mix autonumeric values with key-values, but autonumeric must be declared first:
>>> f = Fact('x', 'y', 'z', a=1, b=2)
>>> f[1]
'y'
>>> f['b']
2
5. You can subclass Fact to express different kinds of data or extend it with your custom functionality.
class Alert(Fact):
"""The alert level."""
pass
class Status(Fact):
"""The system status."""
pass
f1 = Alert('red')
f2 = Status('critical')
class User(Fact):
@classmethod
def from_django_model(cls, obj):
return cls(pk=obj.pk,
name=obj.name,
email=obj.email)
def save_to_db(self):
return DjangoUser.create(**self)
6. Fact fields can be validated automatically for you if you define them using Field. Field uses the Schema library
internally for data validation. Also, a field can be declared mandatory or have a default.
3.3.2 Rules
class MyFact(Fact):
pass
@Rule(Fact('animal', family='felinae'))
def match_with_cats():
"""
Match with every `Fact` which:
* f[0] == 'animal'
* f['family'] == 'felinae'
@Rule(
AND(
OR(User('admin'),
User('root')),
NOT(Fact('drop-privileges'))
)
)
def the_user_has_power():
"""
The user is a privileged one and we are not dropping privileges.
"""
enable_superpowers()
Note: For a list of more complex operators you can check the experta.operator module.
Facts vs Patterns
The difference between Facts and Patterns is small. In fact, Patterns are just Facts containing Pattern Conditional
Elements instead of regular data. They are used only in the LHS of a rule.
If you don’t provide the content of a pattern as a PCE, Experta will enclose the value in a LiteralPCE automatically
for you.
Also, you can’t declare any Fact containing a PCE, if you do, you will receive a nice exception back.
>>> ke = KnowledgeEngine()
>>> ke.declare(Fact(L("hi")))
Traceback (most recent call last):
File "<ipython-input-4-b36cff89278d>", line 1, in <module>
ke.declare(Fact(L('hi')))
File "/home/experta/experta/engine.py", line 210, in declare
self.__declare(*facts)
File "/home/experta/experta/engine.py", line 191, in __declare
"Declared facts cannot contain conditional elements")
TypeError: Declared facts cannot contain conditional elements
3.3.3 DefFacts
Most of the time expert systems needs a set of facts to be present for the system to work. This is the purpose of the
DefFacts decorator.
@DefFacts()
def needed_data():
yield Fact(best_color="red")
(continues on next page)
All DefFacts inside a KnowledgeEngine will be called every time the reset method is called.
New in version 1.7.0: The reset() method accepts any number of keyword parameters whose gets passed to DefFacts
decorated methods if those methods present the same parameters.
3.3.4 KnowledgeEngine
Listing 1: greet.py
from experta import *
class Greetings(KnowledgeEngine):
@DefFacts()
def _initial_action(self):
yield Fact(action="greet")
@Rule(Fact(action='greet'),
NOT(Fact(name=W())))
def ask_name(self):
self.declare(Fact(name=input("What's your name? ")))
@Rule(Fact(action='greet'),
NOT(Fact(location=W())))
def ask_location(self):
self.declare(Fact(location=input("Where are you? ")))
@Rule(Fact(action='greet'),
Fact(name=MATCH.name),
Fact(location=MATCH.location))
def greet(self, name, location):
print("Hi %s! How is the weather in %s?" % (name, location))
engine = Greetings()
engine.reset() # Prepare the engine for the execution.
engine.run() # Run it!
$ python greet.py
What's your name? Roberto
Where are you? Madrid
Hi Roberto! How is the weather in Madrid?
Handling facts
The following methods are used to manipulate the set of facts the engine knows about.
declare
Adds a new fact to the factlist (the list of facts known by the engine).
Note: The same fact can’t be declared twice unless facts.duplication is set to True.
retract
Listing 2: Both, the index and the fact can be used with retract
>>> engine.facts
<f-0> InitialFact()
<f-1> Fact(score=5)
<f-2> Fact(color='red')
>>> engine.retract(1)
>>> engine.facts
<f-0> InitialFact()
<f-2> Fact(color='red')
modify
Retracts some fact from the factlist and declares a new one with some changes. Changes are passed as arguments.
>>> engine.facts
<f-0> InitialFact()
<f-1> Fact(color='red')
>>> engine.modify(engine.facts[1], color='yellow', blink=True)
<f-2>
>>> engine.facts
<f-0> InitialFact()
<f-2> Fact(color='yellow', blink=True)
duplicate
Adds a new fact to the factlist using an existing fact as a template and adding some modifications.
>>> engine.facts
<f-0> InitialFact()
<f-1> Fact(color='red')
>>> engine.duplicate(engine.facts[1], color='yellow', blink=True)
<f-2>
>>> engine.facts
<f-0> InitialFact()
<f-1> Fact(color='red')
<f-2> Fact(color='yellow', blink=True)
Cycle of execution
In a conventional programming style, the starting point, the stopping point, and the sequence of operations are defined
explicitly by the programmer. With Experta, the program flow does not need to be defined quite so explicitly. The
knowledge (Rules) and the data (Facts) are separated, and the KnowledgeEngine is used to apply the knowledge to the
data.
The basic execution cycle is as follows:
1. If the rule firing limit has been reached the execution is halted.
2. The top rule on the agenda is selected for execution. If there are no rules on the agenda, the execution is halted.
3. The RHS actions of the selected rule are executed (the method is called). As a result, rules may be activated
or deactivated. Activated rules (those rules whose conditions are currently satisfied) are placed on the agenda.
The placement on the agenda is determined by the salience of the rule and the current conflict resolution
strategy. Deactivated rules are removed from the agenda.
3.4 Reference
The following diagram shows all the system components and the relationships among them.
3.4. Reference 13
experta Documentation, Release unknown
Fact
retract declare
KnowledgeEngine contains
has has
organize
contains Agenda
Activation
contains contains
Rule Context
contains
contains
Pattern
contains
3.4.1 Rule
Rule is the basic method of composing patterns. You can add as many patterns or conditional elements as you want to
a Rule and it will fire if every one of them matches. Therefore, it behaves like AND by default.
@Rule(<pattern_1>,
<pattern_2>,
...
<pattern_n>)
def _():
pass
3.4. Reference 15
experta Documentation, Release unknown
Rule
contains
contains
Pattern
contains
Composable FC
contains
&, |, ~
contains
salience
This value, by default 0, determines the priority of the rule in relation to the others. Rules with a higher salience will
be fired before rules with a lower one.
@Rule(salience=0)
def r2():
pass
AND
AND creates a composed pattern containing all Facts passed as arguments. All of the passed patterns must match for
the composed pattern to match.
Listing 4: Match if two facts are declared, one matching Fact(1) and
other matching Fact(2)
@Rule(AND(Fact(1),
Fact(2)))
def _():
pass
OR
OR creates a composed pattern in which any of the given pattern will make the rule match.
Warning: If multiple facts match, the rule will be fired multiple times, one for each valid combination of matching
facts.
NOT
This element matches if the given pattern does not match with any fact or combination of facts. Therefore this element
matches the absence of the given pattern.
3.4. Reference 17
experta Documentation, Release unknown
TEST
Check the received callable against the current binded values. If the execution returns True the evaluation will continue
and stops otherwise.
EXISTS
This CE receives a pattern and matches if one or more facts matches this pattern. This will match only once while one
or more matching facts exists and will stop matching when there is no matching facts.
FORALL
The FORALL conditional element provides a mechanism for determining if a group of specified CEs is satisfied for
every occurence of another specified CE.
Listing 9: Match when for every Student fact there is a Reading, Writing
and Arithmetic fact with the same name.
@Rule(FORALL(Student(MATCH.name),
Reading(MATCH.name),
Writing(MATCH.name),
Arithmetic(MATCH.name)))
def all_students_passed():
pass
Note: All binded variables captured inside a FORALL clause won’t be passed as context to the RHS of the rule.
Note: Any time the rule is activated the matching fact is the InitialFact.
This element performs an exact match with the given value. The matching is done using the equality operator ==.
Note: This is the default FC used when no FC is given as a pattern value. pattern.
Listing 11: Match if some fact is declared with the key mykey.
@Rule(Fact(mykey=W()))
def _():
pass
The match of this element is the result of applying the given callable to the fact-extracted value. If the callable returns
True the FC will match, in other case the FC will not match.
All FC can be composed together using the composition operators &, | and ~.
3.4. Reference 19
experta Documentation, Release unknown
ORFC() a.k.a. |
NOTFC() a.k.a. ~
This composed FC negates the given FC, reversing the logic. If the given FC matches this will not and vice versa.
Any pattern and some FCs can be binded to a name using the << operator.
Listing 16: The first value of the matching fact will be binded to the name
value and passed to the function when fired.
@Rule(Fact('value' << W()))
def _(value):
pass
Listing 17: The whole matching fact will be binded to f1 and passed to
the function when fired.
@Rule('f1' << Fact())
def _(f1):
pass
The MATCH objects helps generating more readable name bindings. Is syntactic sugar for a Wildcard Field Constraint
binded to a name. For example:
@Rule(Fact(MATCH.myvalue))
def _(myvalue):
pass
3.4.7 AS object
The AS object like the MATCH object is syntactic sugar for generating bindable names. In this case any attribute
requested to the AS object will return a string with the same name.
Warning: This behavior will vary in future releases of Experta and the string flavour of the operator may disap-
pear.
Nested matching take the form field__subkey=value. (That’s a double-underscore). For example:
Is possible to match against an arbitrary deep structure following the same method.
3.4. Reference 21
experta Documentation, Release unknown
In this example we can check for collision between a ship and its parent with the following rule:
>>> @Rule(Ship(data__name=MATCH.name1,
... data__position__x=MATCH.x,
... data__position__y=MATCH.y,
... data__parent__name=MATCH.name2,
... data__parent__position__x=MATCH.x,
... data__parent__position__y=MATCH.y))
... def collision_detected(self, name1, name2, **_):
... print("COLLISION!", name1, name2)
If the nested data structure contains list, tuples or any other sequence you can use numeric indexes as needed.
>>> Ship(data={
... "name": "SmallShip",
... "position": {
... "x": 300,
... "y": 200},
... "enemies": [
... {"name": "Destroyer"},
... {"name": "BigShip"}]})
>>>
>>> @Rule(Ship(data__enemies__0__name="Destroyer"))
... def next_enemy_is_destroyer(self):
... print("Bye byee!")
Experta’s matching algorithm depends on the values of the declared facts being immutable.
When a Fact is created, all its values are transformed to an immutable type if they are not. For this matter the method
experta.utils.freeze is used internally.
>>> class MutableTest(KnowledgeEngine):
... @Rule(Fact(v1=MATCH.v1, v2=MATCH.v2, v3=MATCH.v3))
... def is_immutable(self, v1, v2, v3):
... print(type(v1), "is Immutable!")
... print(type(v2), "is Immutable!")
... print(type(v3), "is Immutable!")
...
>>> ke = MutableTest()
>>> ke.reset()
(continues on next page)
Note: You can import frozendict and frozenlist from experta.utils module. However frozenset is a Python built-in
type.
If you need to include your own custom mutable types as fact values you have to register a specialized type freezer for
your custom type.
Note: The same freeze registration procedure shown above also applies to unfreeze.
3.5 Cookbook
3.5. Cookbook 23
experta Documentation, Release unknown
CHAPTER 4
API Documentation
4.1.1 experta
4.1.2 experta.abstract
4.1.3 experta.activation
4.1.4 experta.agenda
4.1.5 experta.conditionalelement
4.1.6 experta.engine
4.1.7 experta.factlist
4.1.8 experta.fact
4.1.9 experta.fieldconstraint
4.1.10 experta.rule
4.1.11 experta.strategies
4.1.12 experta.watchers
4.1.13 experta.matchers
4.1.14 experta.matchers.rete
4.1.15
26 experta.matchers.rete.abstract Chapter 4. API Documentation
4.1.16 experta.matchers.rete.check
CHAPTER 5
Release History
27
experta Documentation, Release unknown
CHANGELOG
6.1 1.9.3
• Resolve #11 that was introduced with #7, that caused the same behavior under different conditions.
6.2 1.9.2
• Resolved #7. In some situations last activation was removed right after entering the agenda.
6.3 1.9.1
• Resolved #3. Rules should not be called with already retracted facts.
6.4 1.9.0
6.5 1.8.0-1.8.2
• Rebranded to Experta.
29
experta Documentation, Release unknown
6.6 1.7.0
6.7 1.6.0
6.8 1.5.0
6.9 1.4.0
6.10 1.3.0
• pyknow.operator module.
• Nested matching.
• Added Talk ‘Sistemas Expertos en Python con PyKnow - PyConES 2017’ to docs folder.
6.11 1.2.0
30 Chapter 6. CHANGELOG
experta Documentation, Release unknown
6.12 1.1.1
6.13 1.1.0
6.14 1.0.1
6.15 1.0.0
6.16 <1.0.0
• Unestable API.
• Wrong matching algorithm.
• Bad performance
• PLEASE DON’T USE THIS.
6.12. 1.1.1 31
experta Documentation, Release unknown
32 Chapter 6. CHANGELOG
CHAPTER 7
Source documentation
• genindex
• modindex
• search
33