Pyknow Documentation: Release 1.5.0
Pyknow Documentation: Release 1.5.0
Release 1.5.0
1 User Guide 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 Difference between CLIPS and PyKnow . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 From PyPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Getting the source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.3 DefFacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.4 KnowledgeEngine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4 Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4.1 Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4.2 Conditional Elements: Composing Patterns Together . . . . . . . . . . . . . . . . . . . . . 13
1.4.3 Field Constraints: FC for sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4.4 Composing FCs: &, | and ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4.5 Variable Binding: The << Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.4.6 MATCH object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.4.7 AS object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.4.8 Nested matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.4.9 Mutable objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.5 Cookbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2 API Documentation 21
2.1 Modules documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.1 pyknow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.2 pyknow.abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.3 pyknow.activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.4 pyknow.agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.5 pyknow.conditionalelement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.6 pyknow.engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.7 pyknow.factlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.1.8 pyknow.fact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.1.9 pyknow.fieldconstraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
i
2.1.10 pyknow.rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.1.11 pyknow.strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.1.12 pyknow.watchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.1.13 pyknow.matchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.1.14 pyknow.matchers.rete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.1.15 pyknow.matchers.rete.abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.1.16 pyknow.matchers.rete.check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.1.17 pyknow.matchers.rete.dnf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.1.18 pyknow.matchers.rete.mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.1.19 pyknow.matchers.rete.nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.1.20 pyknow.matchers.rete.token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.1.21 pyknow.matchers.rete.utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.1.22 pyknow.operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3 Release History 33
3.1 1.5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2 1.4.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3 1.3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.4 1.2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.5 1.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.6 1.1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.7 1.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.8 1.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.9 <1.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4 Source documentation 35
ii
pyknow Documentation, Release 1.5.0
PyKnow 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
pyknow Documentation, Release 1.5.0
2 Contents
CHAPTER 1
User Guide
1.1 Introduction
1.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.
1.1.2 Features
• Python 3 compatible.
• Pure Python implementation.
• Matcher based on the RETE algorithm.
1. CLIPS is a programming language, PyKnow 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, PyKnow 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.
1.2 Installation
3
pyknow Documentation, Release 1.5.0
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.
1.3.1 Facts
Facts are the basic unit of information of PyKnow. 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)
1.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'
"""
print("Meow!")
@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 pyknow.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, PyKnow 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/pyknow/pyknow/engine.py", line 210, in declare
self.__declare(*facts)
File "/home/pyknow/pyknow/engine.py", line 191, in __declare
"Declared facts cannot contain conditional elements")
TypeError: Declared facts cannot contain conditional elements
1.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")
yield Fact(best_body="medium")
yield Fact(best_sweetness="dry")
All DefFacts inside a KnowledgeEngine will be called every time the reset method is called.
1.3.4 KnowledgeEngine
Listing 1: greet.py
from pyknow 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)
Because this topic is often a direct cause of misunderstanding, it deserves a special mention here, in the basics.
For a KnowledgeEngine to run, this things must happen:
1. The class must be instantiated, of course.
2. The reset method must be called:
• This declares the special fact InitialFact. Necessary for some rules to work properly.
• Declare all facts yielded by the methods decorated with @DefFacts.
3. The run method must be called. This starts the cycle of execution.
1.4 Reference
The following diagram shows all the system components and the relationships among them.
1.4. Reference 9
pyknow Documentation, Release 1.5.0
Fact
retract declare
KnowledgeEngine contains
has has
organize
contains Agenda
Activation
contains contains
Rule Context
contains
contains
Pattern
contains
1.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
1.4. Reference 11
pyknow Documentation, Release 1.5.0
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.
1.4. Reference 13
pyknow Documentation, Release 1.5.0
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 ~.
1.4. Reference 15
pyknow Documentation, Release 1.5.0
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
1.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 PyKnow and the string flavour of the operator may
disappear.
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.
1.4. Reference 17
pyknow Documentation, Release 1.5.0
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!")
PyKnow’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
pyknow.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 pyknow.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.
1.5 Cookbook
1.5. Cookbook 19
pyknow Documentation, Release 1.5.0
API Documentation
2.1.1 pyknow
2.1.2 pyknow.abstract
class pyknow.abstract.Matcher(engine)
Bases: object
changes(adding=None, deleting=None)
Main interface with the matcher.
Called by the knowledge engine when changes are made in the working memory and return a set of
activations. ﯾﺗم اﺳﺗدﻋﺎؤه ﺑواﺳطﺔ ﻣﺣرك اﻟﻣﻌرﻓﺔ ﻋﻧد إﺟراء اﻟﺗﻐﯾﯾرات ﻓﻲ اﻟذاﻛرة اﻟﻌﺎﻣﻠﺔ وإرﺟﺎع ﻣﺟﻣوﻋﺔ ﻣن ﻋﻣﻠﯾﺎت اﻟﺗﻧﺷﯾط.
reset()
Reset the matcher memory.
class pyknow.abstract.Strategy(*args, **kwargs)
Bases: object
update_agenda(agenda, added, removed)
2.1.3 pyknow.activation
ﺗﻣﺛل ﻋﻣﻠﯾﺎت اﻟﺗﻧﺷﯾط اﻟﻘواﻋد اﻟﺗﻲ ﺗﺗواﻓﻖ ﻣﻊ ﻗﺎﺋﻣﺔ ﺣﻘﺎﺋﻖ ﻣﺣددة.
Activations represent rules that matches against a specific factlist.
class pyknow.activation.Activation(rule, facts, context=None)
Bases: object
Activation object
21
pyknow Documentation, Release 1.5.0
2.1.4 pyknow.agenda
class pyknow.agenda.Agenda
Bases: object
ﻣﺟﻣوﻋﺔ ﻣن ﻋﻣﻠﯾﺎت اﻟﺗﻧﺷﯾط اﻟﺗﻲ ﺗﺗﻌﺎﻣل ﻣﻊ ﺣﺎﻟﺔ اﻟﺗﻧﻔﯾذ اﻟﺧﺎﺻﺔ ﺑﮭﺎ
Collection of activations that handles its execution state.
get_next()
Returns the next activation, removes it from activations list.
2.1.5 pyknow.conditionalelement
class pyknow.conditionalelement.AND
Bases: pyknow.conditionalelement.OperableCE, pyknow.conditionalelement.
ConditionalElement
class pyknow.conditionalelement.OR
Bases: pyknow.conditionalelement.OperableCE, pyknow.conditionalelement.
ConditionalElement
class pyknow.conditionalelement.NOT
Bases: pyknow.conditionalelement.OperableCE, pyknow.conditionalelement.
ConditionalElement
class pyknow.conditionalelement.TEST
Bases: pyknow.conditionalelement.OperableCE, pyknow.conditionalelement.
ConditionalElement
class pyknow.conditionalelement.EXISTS
Bases: pyknow.conditionalelement.OperableCE, pyknow.conditionalelement.
ConditionalElement
class pyknow.conditionalelement.FORALL
Bases: pyknow.conditionalelement.OperableCE, pyknow.conditionalelement.
ConditionalElement
2.1.6 pyknow.engine
duplicate(template_fact, **modifiers)
Create a new fact from an existing one.
get_activations()
Return activations
get_deffacts()
Return the existing deffacts sorted by the internal order
get_rules()
Return the existing rules.
halt()
modify(declared_fact, **modifiers)
Modifies a fact.
Facts are inmutable in Clips, thus, as documented in clips reference manual, this retracts a fact and then
re-declares it
modifiers must be a Mapping object containing keys and values to be changed.
To allow modifying positional facts, the user can pass a string containing the symbol “_” followed by the
numeric index (starting with 0). Ex:
reset()
Performs a reset as per CLIPS behaviour (resets the agenda and factlist and declares InitialFact())
retract(idx_or_declared_fact)
Retracts a specific fact, using its index
run(steps=inf )
Execute agenda activations
2.1.7 pyknow.factlist
A factlist acts as both the module’s factlist and a fact-set yet currently most methods from a fact-set
are not yet implemented
changes
Return a tuple with the removed and added facts since last run.
declare(fact)
Assert (in clips terminology) a fact.
This keeps insertion order.
Warning: This will reject any object that not descend from the Fact class.
retract(idx_or_fact)
Retract a previously asserted fact.
See “Retract that fact” in Clips User Guide.
Parameters idx – The index of the fact to retract in the factlist
Returns (int) The retracted fact’s index
Throws IndexError If the fact’s index providen does not exist
2.1.8 pyknow.fact
2.1.9 pyknow.fieldconstraint
class pyknow.fieldconstraint.L
Bases: pyknow.pattern.Bindable, pyknow.fieldconstraint.FieldConstraint
Literal Field Constraint
value
class pyknow.fieldconstraint.W
Bases: pyknow.pattern.Bindable, pyknow.fieldconstraint.FieldConstraint
Wildcard Field Constraint
class pyknow.fieldconstraint.P
Bases: pyknow.pattern.Bindable, pyknow.fieldconstraint.FieldConstraint
Predicate Field Constraint
match
2.1.10 pyknow.rule
class pyknow.rule.Rule
Bases: pyknow.conditionalelement.ConditionalElement
Base CE, all CE are to derive from this class.
This class is used as a decorator, thus provoking __call__ to be called twice:
1. The first call is when the decorator is been created. At this point we assign the function decorated to
self._wrapped and return self to be called the second time.
2. The second call is to execute the decorated function, se we pass all the arguments along.
new_conditions(*args)
Generate a new rule with the same attributes but with the given conditions.
2.1.11 pyknow.strategies
2.1.12 pyknow.watchers
Watchers are loggers that log detailed information on CLIPS, disabled by default and that can be enabled by the
(watch) method.
Here, we expose a rule, fact and agenda watchers as well as a method to enable/disable them both individually and all
of them.
pyknow.watchers.watch(*what, level=10)
Enable watchers.
Defaults to enable all watchers, accepts a list names of watchers to enable.
pyknow.watchers.unwatch(*what)
Disable watchers.
Defaults to enable all watchers, accepts a list names of watchers to enable.
2.1.13 pyknow.matchers
2.1.14 pyknow.matchers.rete
2.1.15 pyknow.matchers.rete.abstract
class pyknow.matchers.rete.abstract.OneInputNode
Bases: pyknow.matchers.rete.abstract.Node
Nodes which only have one input port.
activate(token)
Make a copy of the received token and call self._activate.
class pyknow.matchers.rete.abstract.TwoInputNode
Bases: pyknow.matchers.rete.abstract.Node
Nodes which have two input ports: left and right.
activate_left(token)
Make a copy of the received token and call _activate_left.
activate_right(token)
Make a copy of the received token and call _activate_right.
2.1.16 pyknow.matchers.rete.check
class pyknow.matchers.rete.check.TypeCheck
Bases: pyknow.matchers.rete.abstract.Check, pyknow.matchers.rete.check.
_TypeCheck
class pyknow.matchers.rete.check.WhereCheck
Bases: pyknow.matchers.rete.abstract.Check, pyknow.matchers.rete.check.
_WhereCheck
2.1.17 pyknow.matchers.rete.dnf
2.1.18 pyknow.matchers.rete.mixins
2.1.19 pyknow.matchers.rete.nodes
class pyknow.matchers.rete.nodes.OrdinaryMatchNode(matcher)
Bases: pyknow.matchers.rete.mixins.AnyChild, pyknow.matchers.rete.mixins.
HasMatcher, pyknow.matchers.rete.abstract.TwoInputNode
Ordinary Two-input Node.
This kind of node receive tokens at two ports (left and right) and try to match them.
The matching function is a callable given as a parameter to __init__ and stored internally. This functions will
receive two contexts, one from the left and other from the right, and decides if they match together (returning
True or False).
Matching pairs will be combined in one token containing facts from both and a combined context. This com-
bined tokens will be sent to all children.
class pyknow.matchers.rete.nodes.WhereNode(matcher)
Bases: pyknow.matchers.rete.mixins.AnyChild, pyknow.matchers.rete.mixins.
HasMatcher, pyknow.matchers.rete.mixins.NoMemory, pyknow.matchers.rete.
abstract.OneInputNode
Check some conditions over a token context.
2.1.20 pyknow.matchers.rete.token
to_invalid_token()
Create an INVALID token using this data.
to_valid_token()
Create a VALID token using this data.
2.1.21 pyknow.matchers.rete.utils
pyknow.matchers.rete.utils.extract_facts(rule)
Given a rule, return a set containing all rule LHS facts.
pyknow.matchers.rete.utils.generate_checks(fact)
Given a fact, generate a list of Check objects for checking it.
pyknow.matchers.rete.utils.prepare_rule(exp)
Given a rule, build a new one suitable for RETE network generation.
Meaning:
1. Rule is in disjuntive normal form (DNF).
2. If the rule is empty is filled with an InitialFact.
3. If the rule starts with a NOT, an InitialFact is prepended.
4. If any AND starts with a NOT, an InitialFact is prepended.
#. If the rule is an OR condition, each NOT inside will be converted to AND(InitialFact(), NOT(. . . ))
pyknow.matchers.rete.utils.wire_rule(rule, alpha_terminals, lhs=None)
2.1.22 pyknow.operator
The operator module contains a set of predicate functions constructors based on the P() field constraint.
These operators can be composed together and binded like normal Field Constraints.
Example:
pyknow.operator.LT(b)
Less than operator.
pyknow.operator.LE(b)
Less than or equal operator.
pyknow.operator.EQ(b)
Equal operator.
pyknow.operator.NE(b)
Not equal operator.
pyknow.operator.GE(b)
Greater than or equal operator.
pyknow.operator.GT(b)
Greater than operator.
pyknow.operator.IS(b)
Tests object identity.
pyknow.operator.IS_NOT(b)
Tests object identity.
pyknow.operator.CONTAINS(b)
Return the outcome of the test b in a
pyknow.operator.BETWEEN(a, b)
The BETWEEN operator selects values within a given range. The BETWEEN operator is inclusive: begin and
end values are included.
pyknow.operator.REGEX(pattern, flags=0)
Regular expression matching.
pyknow.operator.LIKE(pattern)
Unix shell-style wildcards. Case-sensitive
pyknow.operator.ILIKE(pattern)
Unix shell-style wildcards. Case-insensitive
Release History
3.1 1.5.0
3.2 1.4.0
3.3 1.3.0
• pyknow.operator module.
• Nested matching.
• Added Talk ‘Sistemas Expertos en Python con PyKnow - PyConES 2017’ to docs folder.
33
pyknow Documentation, Release 1.5.0
3.4 1.2.0
3.5 1.1.1
3.6 1.1.0
3.7 1.0.1
3.8 1.0.0
3.9 <1.0.0
• Unestable API.
• Wrong matching algorithm.
• Bad performance
• PLEASE DON’T USE THIS.
Source documentation
• genindex
• modindex
• search
35
pyknow Documentation, Release 1.5.0
p
pyknow, 21
pyknow.abstract, 21
pyknow.activation, 21
pyknow.agenda, 22
pyknow.conditionalelement, 22
pyknow.engine, 22
pyknow.fact, 24
pyknow.factlist, 23
pyknow.fieldconstraint, 25
pyknow.matchers, 26
pyknow.matchers.rete, 26
pyknow.matchers.rete.abstract, 26
pyknow.matchers.rete.check, 27
pyknow.matchers.rete.dnf, 28
pyknow.matchers.rete.mixins, 28
pyknow.matchers.rete.nodes, 28
pyknow.matchers.rete.token, 30
pyknow.matchers.rete.utils, 31
pyknow.operator, 31
pyknow.rule, 25
pyknow.strategies, 25
pyknow.watchers, 25
37
pyknow Documentation, Release 1.5.0
39
pyknow Documentation, Release 1.5.0
M R
REGEX() (in module pyknow.operator), 32
match (pyknow.fieldconstraint.P attribute), 25
remove() (pyknow.matchers.rete.nodes.BusNode
Matcher (class in pyknow.abstract), 21
method), 29
modify() (pyknow.engine.KnowledgeEngine method), 23
reset() (pyknow.abstract.Matcher method), 21
N reset() (pyknow.engine.KnowledgeEngine method), 23
reset() (pyknow.matchers.rete.abstract.Node method), 26
NE() (in module pyknow.operator), 32 reset() (pyknow.matchers.rete.ReteMatcher method), 26
new_conditions() (pyknow.rule.Rule method), 25 ReteMatcher (class in pyknow.matchers.rete), 26
Node (class in pyknow.matchers.rete.abstract), 26 retract() (pyknow.engine.KnowledgeEngine method), 23
retract() (pyknow.factlist.FactList method), 24
40 Index
pyknow Documentation, Release 1.5.0
S
SameContextCheck (class in py-
know.matchers.rete.check), 27
show_network() (pyknow.matchers.rete.ReteMatcher
method), 26
Strategy (class in pyknow.abstract), 21
T
TEST (class in pyknow.conditionalelement), 22
to_info() (pyknow.matchers.rete.token.Token method), 30
to_invalid_token() (pyknow.matchers.rete.token.TokenInfo
method), 30
to_valid_token() (pyknow.matchers.rete.token.TokenInfo
method), 31
Token (class in pyknow.matchers.rete.token), 30
Token.TagType (class in pyknow.matchers.rete.token), 30
TokenInfo (class in pyknow.matchers.rete.token), 30
TRUTH (in module pyknow.operator), 31
TwoInputNode (class in pyknow.matchers.rete.abstract),
27
TypeCheck (class in pyknow.matchers.rete.check), 27
U
unpack_exp() (in module pyknow.matchers.rete.dnf), 28
unwatch() (in module pyknow.watchers), 25
update() (pyknow.fact.Fact method), 24
update_agenda() (pyknow.abstract.Strategy method), 21
V
VALID (pyknow.matchers.rete.token.Token.TagType at-
tribute), 30
valid() (pyknow.matchers.rete.token.Token class method),
30
value (pyknow.fieldconstraint.L attribute), 25
W
W (class in pyknow.fieldconstraint), 25
watch() (in module pyknow.watchers), 25
WhereCheck (class in pyknow.matchers.rete.check), 28
WhereNode (class in pyknow.matchers.rete.nodes), 30
wire_rule() (in module pyknow.matchers.rete.utils), 31
Index 41