SlideShare a Scribd company logo
1 of 34
Download to read offline
Expert System With Python
Ahmad Hussein
ahmadhussein.ah7@gmail.com
Lecture 2: The Basics
CONTENT OVERVIEW
• What is CLIPS?
• CLIPS Characteristics.
• What is PyKnow?
• Facts
• DefFacts
• Rules
• Knowledge Engine
• Conditional Elements: Composing Patterns Together.
• Field Constraints: FC for sort.
• Composing FCs: &, | and ~.
• Variable Binding: The << Operator.
What is CLIPS?
• CLIPS is a multiparadigm programming language that provides
support for:
• Rule-based
• Object-oriented
• Procedural programming
CLIPS Characteristics
• CLIPS is an acronym for
• C Language Integrated Production System.
• CLIPS was designed using the C language at the NASA/Johnson Space
Center.
What is PyKnow?
• PyKnow is a Python library alternative to CLIPS.
• Difference between CLIPS and PyKnow:
• CLIPS is a programming language, PyKnow is a Python library. This imposes
some limitations on the constructions we can do (specially on the LHS of a
rule).
• CLIPS is written in C, PyKnow in Python. A noticeable impact in performance is
to be expected.
• In CLIPS you add facts using assert, in Python assert is a keyword, so we use
declare instead.
The Basics
• Facts
• DefFacts
• Rules
• Knowledge Engine
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:
1. The class Fact is a subclass of dict.
f = Fact(a=1, b=2)
print(f['a’])
# 1
Facts
2. Therefore a Fact does not maintain an internal order of items.
f = Fact(a=1, b=2) # Order is arbitrary
# f = Fact(a=1, b=2)
Facts
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')
print(f[0])
# x
Facts
4. You can mix autonumeric values with key-values, but autonumeric
must be declared first.
f = Fact('x', 'y', 'z', a=1, b=2)
print(f[0])
# x
print(f['a’])
# 1
Facts
5. You can subclass Fact to express different kinds of data or extend it
with your custom functionality.
class Alert(Fact):
pass
class Status(Fact):
pass
f1 = Alert(color = 'red')
f2 = Status(state = 'critical')
print(f1['color’]) # red
print(f2['state’]) # 'critical
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.
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.
• All DefFacts inside a KnowledgeEngine will be called every time the reset
method is called.
@DefFacts()
def needed_data():
yield Fact(best_color="red")
yield Fact(best_body="medium")
yield Fact(best_sweetness="dry")
Rules
• In PyKnow a rule is a callable, decorated with Rule.
• Rules have two components, LHS (left-hand-side) and RHS (right-
hand-side).
• The LHS describes (using patterns) the conditions on which the rule * should
be executed (or fired).
• The RHS is the set of actions to perform when the rule is fired.
• For a Fact to match a Pattern, all pattern restrictions must be True
when the Fact is evaluated against it.
Rules
Example:
• This rule will match with every instance of ‘MyFact’.
class MyFact (Fact):
pass
@Rule(MyFact()) # This is the LHS
def matchWithEveryMyfact():
# This is the RHS
pass
Rules
Example:
• Match with every Fact which:
• f[0] == 'animal'
• f['family'] == 'felinae'
class MyFact (Fact):
pass
@Rule(Fact('animal', family='felinae’))
def match_with_cats ():
print("Meow!")
Rules
Example:
• The user is a privileged one and we are not dropping privileges.
@Rule((User('admin') | User('root’))
& ~Fact('drop-privileges'))
def the_user_has_power():
enable_superpowers()
KnowledgeEngine
• This is the place where all the magic happens.
• The first step is to make a subclass of it and use Rule to decorate its
methods.
• After that, you can instantiate it, populate it with facts, and finally run
it.
KnowledgeEngine
Example:
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? ")))
continue
KnowledgeEngine
Example:
@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="name" << W()),
Fact(location="location" << W()))
def greet(self, name, location):
print("Hi %s! How is the weather in %s?" % (name, location))
continue
KnowledgeEngine
Example:
engine = Greetings()
engine.reset() # Prepare the engine for the execution.
engine.run() # Run it!
Output:
What's your name? Roberto
Where are you? Madrid
Hi Roberto! How is the weather in Madrid?
Conditional Elements: Composing Patterns Together
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.
• Match if two facts are declared, one matching Fact(1) and other
matching Fact(2).
@Rule(AND(Fact(1),Fact(2)))
def _():
pass
Conditional Elements: Composing Patterns Together
OR:
• OR creates a composed pattern in which any of the given pattern will
make the rule match.
• Match if a fact matching Fact(1) exists and/or a fact matching Fact(2)
exists.
@Rule(OR(Fact(1),Fact(2)))
def _():
pass
Conditional Elements: Composing Patterns Together
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.
• Match if no fact match with Fact(1).
@Rule(NOT(Fact(1))
def _():
pass
Conditional Elements: Composing Patterns Together
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.
• Match once when one or more Color exists.
@Rule(EXISTS(Color()))
def _():
pass
Conditional Elements: Composing Patterns Together
FORALL:
• The FORALL conditional element provides a mechanism for
determining if a group of specified CEs is satisfied for every
occurrence of another specified CE.
• Match once when one or more Color exists.
@Rule(FORALL(Student(W('name')),
Reading(W('name')),
Writing(W('name')),
Arithmetic(W('name')))
def all_students_passed():
pass
Field Constraints: FC for sort
L (Literal Field Constraint):
• This element performs an exact match with the given value. The
matching is done using the equality operator ==.
• Match if the first element is exactly 3.
@Rule(Fact(L(3)))
def _():
pass
Field Constraints: FC for sort
W (Wildcard Field Constraint):
• This element matches with any value.
• Match if some fact is declared with the key mykey.
@Rule(Fact(mykey=W()))
def _():
pass
Field Constraints: FC for sort
P (Predicate Field Constraint):
• 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.
• Match if some fact is declared whose first parameter is an instance of
int.
@Rule(Fact(P(lambda x: isinstance(x, int))))
def _():
pass
Composing FCs: &, | and ~
ANDFC() - &:
• The composed FC matches if all the given FC match.
• Match if key x of Point is a value between 0 and 255.
@Rule(x=P(lambda x: x >= 0) & P(lambda x: x <= 255)))
def _():
pass
Composing FCs: &, | and ~
ORFC() - |:
• The composed FC matches if any of the given FC matches.
• Match if name is either Alice or Bob.
@Rule(Fact(name=L('Alice') | L('Bob’)))
def _():
pass
Composing FCs: &, | and ~
NOTFC() - ~:
• This composed FC negates the given FC, reversing the logic. If the
given FC matches this will not and vice versa.
• Match if name is not Charlie.
@Rule(Fact(name=~L('Charlie')))
def _():
pass
Variable Binding: The << Operator
• Any patterns and some FCs can be binded to a name using the <<
operator.
• Example 1:
• 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
Variable Binding: The << Operator
• Any patterns and some FCs can be binded to a name using the <<
operator.
• Example 2:
• The whole matching fact will be binded to f1 and passed to the
function when fired.
@Rule(Fact(‘f1' << Fact())
def _(f1):
pass

More Related Content

What's hot

[Cloud OnAir] AI の力で次世代型コンタクトセンターへ 〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...
[Cloud OnAir] AI の力で次世代型コンタクトセンターへ  〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...[Cloud OnAir] AI の力で次世代型コンタクトセンターへ  〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...
[Cloud OnAir] AI の力で次世代型コンタクトセンターへ 〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...Google Cloud Platform - Japan
 
Keras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | Edureka
Keras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | EdurekaKeras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | Edureka
Keras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | EdurekaEdureka!
 
C format string vulnerability
C format string vulnerabilityC format string vulnerability
C format string vulnerabilitysluge
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Edureka!
 
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)Clément Wehrung
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1Mohammed Hussein
 
モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)
モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)
モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)株式会社MonotaRO Tech Team
 
Introduction to ELK
Introduction to ELKIntroduction to ELK
Introduction to ELKYuHsuan Chen
 
Spark Streaming + Amazon Kinesis
Spark Streaming + Amazon KinesisSpark Streaming + Amazon Kinesis
Spark Streaming + Amazon KinesisYuta Imai
 
Introduction to elasticsearch
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearchpmanvi
 
ElasticSearch Basic Introduction
ElasticSearch Basic IntroductionElasticSearch Basic Introduction
ElasticSearch Basic IntroductionMayur Rathod
 

What's hot (20)

[Cloud OnAir] AI の力で次世代型コンタクトセンターへ 〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...
[Cloud OnAir] AI の力で次世代型コンタクトセンターへ  〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...[Cloud OnAir] AI の力で次世代型コンタクトセンターへ  〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...
[Cloud OnAir] AI の力で次世代型コンタクトセンターへ 〜 Contact Center AI ソリューションにおけるジェネシス・ジャパン...
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Keras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | Edureka
Keras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | EdurekaKeras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | Edureka
Keras vs Tensorflow vs PyTorch | Deep Learning Frameworks Comparison | Edureka
 
C format string vulnerability
C format string vulnerabilityC format string vulnerability
C format string vulnerability
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
 
Css padding
Css paddingCss padding
Css padding
 
Database programming
Database programmingDatabase programming
Database programming
 
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Ai use cases
Ai use casesAi use cases
Ai use cases
 
PHP
PHPPHP
PHP
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1
 
Control structures
Control structuresControl structures
Control structures
 
モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)
モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)
モノタロウの1900万商品を検索する Elasticsearch構築運用事例(2022-10-26 第50回Elasticsearch 勉強会発表資料)
 
Introduction to ELK
Introduction to ELKIntroduction to ELK
Introduction to ELK
 
Spark Streaming + Amazon Kinesis
Spark Streaming + Amazon KinesisSpark Streaming + Amazon Kinesis
Spark Streaming + Amazon Kinesis
 
Pytorch
PytorchPytorch
Pytorch
 
Introduction to elasticsearch
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearch
 
ElasticSearch Basic Introduction
ElasticSearch Basic IntroductionElasticSearch Basic Introduction
ElasticSearch Basic Introduction
 

Similar to Expert system with python -2

Introduction to Boost regex
Introduction to Boost regexIntroduction to Boost regex
Introduction to Boost regexYongqiang Li
 
An Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewAn Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewBlue Elephant Consulting
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
LecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfLecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfAmirMohamedNabilSale
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional ProgrammingSartaj Singh
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptxrohithprabhas1
 
Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03Avelin Huo
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismEelco Visser
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxSahajShrimal1
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1Syed Farjad Zia Zaidi
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
Python operators (1).pptx
Python operators (1).pptxPython operators (1).pptx
Python operators (1).pptxVaniHarave
 

Similar to Expert system with python -2 (20)

Apriori.pptx
Apriori.pptxApriori.pptx
Apriori.pptx
 
Introduction to Boost regex
Introduction to Boost regexIntroduction to Boost regex
Introduction to Boost regex
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
An Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewAn Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam Review
 
Python Week 1.pptx
Python Week 1.pptxPython Week 1.pptx
Python Week 1.pptx
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
LecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfLecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdf
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Python operators (1).pptx
Python operators (1).pptxPython operators (1).pptx
Python operators (1).pptx
 

More from Ahmad Hussein

Knowledge Representation Methods
Knowledge Representation MethodsKnowledge Representation Methods
Knowledge Representation MethodsAhmad Hussein
 
Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019Ahmad Hussein
 
Knowledge based systems homework
Knowledge based systems homeworkKnowledge based systems homework
Knowledge based systems homeworkAhmad Hussein
 
Expert System With Python -1
Expert System With Python -1Expert System With Python -1
Expert System With Python -1Ahmad Hussein
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
Python introduction 1
Python introduction 1  Python introduction 1
Python introduction 1 Ahmad Hussein
 

More from Ahmad Hussein (7)

Knowledge Representation Methods
Knowledge Representation MethodsKnowledge Representation Methods
Knowledge Representation Methods
 
Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Knowledge based systems homework
Knowledge based systems homeworkKnowledge based systems homework
Knowledge based systems homework
 
Expert System With Python -1
Expert System With Python -1Expert System With Python -1
Expert System With Python -1
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Python introduction 1
Python introduction 1  Python introduction 1
Python introduction 1
 

Recently uploaded

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 

Recently uploaded (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 

Expert system with python -2

  • 1. Expert System With Python Ahmad Hussein ahmadhussein.ah7@gmail.com Lecture 2: The Basics
  • 2. CONTENT OVERVIEW • What is CLIPS? • CLIPS Characteristics. • What is PyKnow? • Facts • DefFacts • Rules • Knowledge Engine • Conditional Elements: Composing Patterns Together. • Field Constraints: FC for sort. • Composing FCs: &, | and ~. • Variable Binding: The << Operator.
  • 3. What is CLIPS? • CLIPS is a multiparadigm programming language that provides support for: • Rule-based • Object-oriented • Procedural programming
  • 4. CLIPS Characteristics • CLIPS is an acronym for • C Language Integrated Production System. • CLIPS was designed using the C language at the NASA/Johnson Space Center.
  • 5. What is PyKnow? • PyKnow is a Python library alternative to CLIPS. • Difference between CLIPS and PyKnow: • CLIPS is a programming language, PyKnow is a Python library. This imposes some limitations on the constructions we can do (specially on the LHS of a rule). • CLIPS is written in C, PyKnow in Python. A noticeable impact in performance is to be expected. • In CLIPS you add facts using assert, in Python assert is a keyword, so we use declare instead.
  • 6. The Basics • Facts • DefFacts • Rules • Knowledge Engine
  • 7. 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: 1. The class Fact is a subclass of dict. f = Fact(a=1, b=2) print(f['a’]) # 1
  • 8. Facts 2. Therefore a Fact does not maintain an internal order of items. f = Fact(a=1, b=2) # Order is arbitrary # f = Fact(a=1, b=2)
  • 9. Facts 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') print(f[0]) # x
  • 10. Facts 4. You can mix autonumeric values with key-values, but autonumeric must be declared first. f = Fact('x', 'y', 'z', a=1, b=2) print(f[0]) # x print(f['a’]) # 1
  • 11. Facts 5. You can subclass Fact to express different kinds of data or extend it with your custom functionality. class Alert(Fact): pass class Status(Fact): pass f1 = Alert(color = 'red') f2 = Status(state = 'critical') print(f1['color’]) # red print(f2['state’]) # 'critical
  • 12. 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.
  • 13. 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. • All DefFacts inside a KnowledgeEngine will be called every time the reset method is called. @DefFacts() def needed_data(): yield Fact(best_color="red") yield Fact(best_body="medium") yield Fact(best_sweetness="dry")
  • 14. Rules • In PyKnow a rule is a callable, decorated with Rule. • Rules have two components, LHS (left-hand-side) and RHS (right- hand-side). • The LHS describes (using patterns) the conditions on which the rule * should be executed (or fired). • The RHS is the set of actions to perform when the rule is fired. • For a Fact to match a Pattern, all pattern restrictions must be True when the Fact is evaluated against it.
  • 15. Rules Example: • This rule will match with every instance of ‘MyFact’. class MyFact (Fact): pass @Rule(MyFact()) # This is the LHS def matchWithEveryMyfact(): # This is the RHS pass
  • 16. Rules Example: • Match with every Fact which: • f[0] == 'animal' • f['family'] == 'felinae' class MyFact (Fact): pass @Rule(Fact('animal', family='felinae’)) def match_with_cats (): print("Meow!")
  • 17. Rules Example: • The user is a privileged one and we are not dropping privileges. @Rule((User('admin') | User('root’)) & ~Fact('drop-privileges')) def the_user_has_power(): enable_superpowers()
  • 18. KnowledgeEngine • This is the place where all the magic happens. • The first step is to make a subclass of it and use Rule to decorate its methods. • After that, you can instantiate it, populate it with facts, and finally run it.
  • 19. KnowledgeEngine Example: 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? "))) continue
  • 20. KnowledgeEngine Example: @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="name" << W()), Fact(location="location" << W())) def greet(self, name, location): print("Hi %s! How is the weather in %s?" % (name, location)) continue
  • 21. KnowledgeEngine Example: engine = Greetings() engine.reset() # Prepare the engine for the execution. engine.run() # Run it! Output: What's your name? Roberto Where are you? Madrid Hi Roberto! How is the weather in Madrid?
  • 22. Conditional Elements: Composing Patterns Together 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. • Match if two facts are declared, one matching Fact(1) and other matching Fact(2). @Rule(AND(Fact(1),Fact(2))) def _(): pass
  • 23. Conditional Elements: Composing Patterns Together OR: • OR creates a composed pattern in which any of the given pattern will make the rule match. • Match if a fact matching Fact(1) exists and/or a fact matching Fact(2) exists. @Rule(OR(Fact(1),Fact(2))) def _(): pass
  • 24. Conditional Elements: Composing Patterns Together 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. • Match if no fact match with Fact(1). @Rule(NOT(Fact(1)) def _(): pass
  • 25. Conditional Elements: Composing Patterns Together 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. • Match once when one or more Color exists. @Rule(EXISTS(Color())) def _(): pass
  • 26. Conditional Elements: Composing Patterns Together FORALL: • The FORALL conditional element provides a mechanism for determining if a group of specified CEs is satisfied for every occurrence of another specified CE. • Match once when one or more Color exists. @Rule(FORALL(Student(W('name')), Reading(W('name')), Writing(W('name')), Arithmetic(W('name'))) def all_students_passed(): pass
  • 27. Field Constraints: FC for sort L (Literal Field Constraint): • This element performs an exact match with the given value. The matching is done using the equality operator ==. • Match if the first element is exactly 3. @Rule(Fact(L(3))) def _(): pass
  • 28. Field Constraints: FC for sort W (Wildcard Field Constraint): • This element matches with any value. • Match if some fact is declared with the key mykey. @Rule(Fact(mykey=W())) def _(): pass
  • 29. Field Constraints: FC for sort P (Predicate Field Constraint): • 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. • Match if some fact is declared whose first parameter is an instance of int. @Rule(Fact(P(lambda x: isinstance(x, int)))) def _(): pass
  • 30. Composing FCs: &, | and ~ ANDFC() - &: • The composed FC matches if all the given FC match. • Match if key x of Point is a value between 0 and 255. @Rule(x=P(lambda x: x >= 0) & P(lambda x: x <= 255))) def _(): pass
  • 31. Composing FCs: &, | and ~ ORFC() - |: • The composed FC matches if any of the given FC matches. • Match if name is either Alice or Bob. @Rule(Fact(name=L('Alice') | L('Bob’))) def _(): pass
  • 32. Composing FCs: &, | and ~ NOTFC() - ~: • This composed FC negates the given FC, reversing the logic. If the given FC matches this will not and vice versa. • Match if name is not Charlie. @Rule(Fact(name=~L('Charlie'))) def _(): pass
  • 33. Variable Binding: The << Operator • Any patterns and some FCs can be binded to a name using the << operator. • Example 1: • 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
  • 34. Variable Binding: The << Operator • Any patterns and some FCs can be binded to a name using the << operator. • Example 2: • The whole matching fact will be binded to f1 and passed to the function when fired. @Rule(Fact(‘f1' << Fact()) def _(f1): pass