当前位置:网站首页>Durable rules (persistent rules engine) learning notes
Durable rules (persistent rules engine) learning notes
2022-07-29 21:00:00 【tumbling little @strong】
1. 写在前面
这篇文章记录下学习durable rules的过程, The Persistence Rules Engine is a polyglot framework, For creating rule-based systems capable of reasoning about large numbers of factual statements,The vernacular is to make some rules in advance, These rules describe the events to match and the action to take. 这样,When the truth comes, You can match events and take appropriate actions. Very similar to what we wrote in our codeif...else if..else的逻辑.
So why use this thing? 快,And it is available in multiple languages,And if judgment is too much,不像if else那么臃肿. The written judgment statement is more elegant.
当然,由于我也是刚学,And there are not many documents available for reference,我就拿github项目来通过3个demoOrganize how to use it,And finally figured it outdemo,Sort out how to actually use it. This operation is used to meet colleagues at the company,It still feels pissed,So it's like studying.
场景:
For example, the conditions for a girl to find a partner: He is handsome and has a house,and high income,And when the occupation is a teacher or a programmer,to date him, Then suppose we have the first few attributes of many boys,Finally, judge the girl's attitude towards him.
这时候,Suppose there is data on boys:{"name": "zhangsan", "age": 25, "job": "teacher", "salary": 2000, "appearance": "good"}, We judge the girl's final attitude, 喜欢,一般,I don't like the three senses.
demo是我自己编的, This is a more common practice,就是写if语句,if ... then ....的这种,But when there are many conditions to judge, This writing seems very cumbersome and bloated, And it's not elegant either,So if the criteria for this girl's selection of objects are fixed,We can write a rule,There will be new data to judge in the future,Just call this rule,就可以.
2. 用法demo理解
2.1 最基本
Here are the ones in the link abovedemo理解.
定义规则,Describes the event or fact pattern to match(先行)and the action to take(后续)
首先,安装包:
pip install durable_rules
我这里发现,If installed in the systempyenv,然后再装conda之后, 发现直接用pip,Will not pack itconda的环境中,而是pyenv的环境中了,So I have to get into the concrete hereconda虚拟环境,Then call that insidepip才行. 否则,在conda里面运行jupyter会报错找不到包,这是因为直接pipwill pack topyenv中.This has to be noted.当然,没有pyenv的直接pip即可.
from durable.lang import *
# 规则名字
with ruleset('test'):
# If this thing matches the previous one,就不往下走了
# antecedent 先行条件
@when_all(m.name == 'wuzhongqiang') # The fields here are the fields in the incoming data
def say_hello(c):
# consequent 后续
print ('Hello {}'.format(c.m.name))
@when_all(m.age > 18)
def young(c):
print("{} 成年了".format(c.m.name))
@when_all(m.sex == "boy")
def sex(c):
print("{} 是个男孩".format(c.m.name))
# Bottom pocket function,That is when none of the above matches, Just go to the bottom
@when_all(+m.sex)
def output(c):
print(c.m.name, c.m.age, c.m.sex)
This is the most basic and most commonly used method,Look at this syntax is also relatively simple, First define a rule name,Then start writing preconditions,and after this precondition is met,触发的行为.
# This matches the first precondition
post('test', {
'name': 'wuzhongqiang', 'age': 25, 'sex': 'boy'})
## Hello wuzhongqiang That is, a precondition is matched,执行之后,Don't forget to leave behind
# Matches the second precondition
post('test', {
'name': 'zhongqiang', 'age': 25, 'sex': 'boy'})
# zhongqiang 成年了
# Does not match all antecedents,Just go to the last bottom-line strategy
post('test', {
'name': 'zhongqiang', 'age': 16, 'sex': 'girl'})
# zhongqiang 16 girl
这个逻辑很简单, 不用多说,但是有两点注意:
- The rule name can only be used once,That is, the above rule defines this code,如果重复定义,会报错,Shows that the rule name is registered,报异常
- Have honest behavior,否则,Assuming that the incoming data does not match the precondition,An error cannot be handled exception will be reported
2.2 assert_fact
This spelling is a bit complicated,讲真,Can't figure out when it will be used, But I can see his example.
This thing is used for forward reasoning,similar to syllogism:
- 如果P, 那么Q
- P出现
- 因此, Q
The example he gave,Actually, I didn't understand it at first,After debugging,Almost got it.
from durable.lang import *
with ruleset('animal'):
@when_all(c.first << (m.predicate == 'eats') & (m.object == 'flies'),
(m.predicate == 'lives') & (m.object == 'water') & (m.subject == c.first.subject))
def frog(c):
print(c.first.subject)
c.assert_fact({
'subject': c.first.subject, 'predicate': 'is', 'object': 'frog' })
@when_all(c.first << (m.predicate == 'eats') & (m.object == 'flies'),
(m.predicate == 'lives') & (m.object == 'land') & (m.subject == c.first.subject))
def chameleon(c):
c.assert_fact({
'subject': c.first.subject, 'predicate': 'is', 'object': 'chameleon' })
@when_all(+m.subject)
def output(c):
print('Fact: {0} {1} {2}'.format(c.m.subject, c.m.predicate, c.m.object))
This actually defines the prerequisites, For example I run the following line of code:
assert_fact('animal', {
'subject': 'Kermit', 'predicate': 'eats', 'object': 'flies' })
这个会输出Fact: Kermit eats flies, This is because of this thing passed in,None of the above preconditions are met(因为只有他自己), But after running this,接下来,If you run the following line of code again:
assert_fact('animal', {
'subject': 'Kermit', 'predicate': 'lives', 'object': 'water' })
the output of this:
Kermit
Fact: Kermit is frog
Fact: Kermit lives water
这个是因为, There is a prerequisite(c.first),That is, the first line of code that runs, Then run the following words again,Exactly matches the first prerequisite
@when_all(c.first << (m.predicate == 'eats') & (m.object == 'flies'),
(m.predicate == 'lives') & (m.object == 'water') & (m.subject == c.first.subject))
def frog(c):
print(c.first.subject)
c.assert_fact({
'subject': c.first.subject, 'predicate': 'is', 'object': 'frog' })
然后都在output那里输出.The above result came out.
And also found a phenomenon,如果先运行
assert_fact('animal', {
'subject': 'Kermit', 'predicate': 'lives', 'object': 'water' })
只会输出Fact: Kermit lives water, 但在这个基础上,再运行
assert_fact('animal', {
'subject': 'Kermit', 'predicate': 'eats', 'object': 'flies' })
This will also output:
Kermit
Fact: Kermit is frog
Fact: Kermit eats flies
It will be the same logic above,就很纳闷,不知道为啥.
But this use case,I understand that there is a precondition that happens first,发生了之后,在做匹配,If the prerequisites are matched, 就会执行相应的语句.
2.3 模式匹配
This is the most basic usage above
from durable.lang import *
with ruleset('pipei'):
@when_all(m.subject.matches('3[47][0-9]{13}'))
def amex(c):
print ('Amex detected {0}'.format(c.m.subject))
@when_all(m.subject.matches('4[0-9]{12}([0-9]{3})?'))
def visa(c):
print ('Visa detected {0}'.format(c.m.subject))
@when_all(m.subject.matches('(5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|2720)[0-9]{12}'))
def mastercard(c):
print ('Mastercard detected {0}'.format(c.m.subject))
So when to use,If the conditions are mutually exclusive,We can write under the same rule.
3. demo
Through a morning of groping,It's not that hard to find this thing,和if…else很像, Below through the opening scenedemo来看看如何用.
实际使用的时候,We generally write the rule engine as a class
class RuleEngine:
def __init__(self, rule_name: str = ''):
if not rule_name:
raise ValueError("rule_name is empty")
self.rule_name = rule_name
def get_result(self, data: dict = None):
if not data:
raise ValueError("data is empty")
output = None
for _ in range(3):
output = post(self.rule_name, data)
if not output is None:
break
if not output is None:
return output.get('result', {
})
else:
print("get_result, return None: {}".format(data))
return {
}
Pass in the rule name,建立对象
attitude_rule = RuleEngine('attitude')
Create a new data
person1 = {
"name": "zhangsan", "age": 25, "job": "teacher", "salary": 2000, "appearance": "good"}
编写规则, 这步是核心
with ruleset("attitude"):
@when_all(
(m.age < 30)
& ((m.salary > 10000) | (m.appearance == "good")) & ((m.job == "teacher") | (m.job == "manong"))
)
def like(c):
c.s.result = {
'attitude_res': 'like',
}
@when_all(
(m.age < 30)
& ((m.salary <= 10000) | (m.appearance == "medium")) & ((m.job == "teacher") | (m.job == "manong"))
)
def yiban(c):
c.s.result = {
'attitude_res': 'yiban',
}
@when_all(+m._age)
def other(c):
c.s.result = {
'attitude_res': 'dislike'
}
然后调用get_resultfunction to get the result
attitude_res = attitude_rule.get_result(person1)
# {'attitude_res': 'like'}
update this to person
person1.update(attitude_res)
person1:
{
'name': 'zhangsan',
'age': 25,
'job': 'teacher',
'salary': 2000,
'appearance': 'good',
'attitude_res': 'like'}
This thing feels like doing new feature columns,也可以用.
这次探索就到这里, Due to the lack of reference materials,Come back to make up for new ones later.
参考
边栏推荐
- MSNs-SS-siRNA二氧化硅-二硫键-核酸RNA|HA-SS-siRNA,hyaluronic acid透明质酸修饰RNA(RNA修饰剂)
- JMeter usage tutorial (2)
- LeetCode_474_一和零
- uri与url的区别简单理解(uri和url有什么区别)
- 荧光量子点修饰siRNA-QDs|纳米金修饰siRNA-Au(RNA修饰方式方法)
- scratch学习相关资料汇总
- R语言对airbnb数据nlp文本挖掘、地理、词云可视化、回归GAM模型、交叉验证分析
- Expert advice | How to formulate a growth strategy for survival in an economic downturn
- Durable rules(持久规则引擎) 学习小记
- 尿素偶联Urea-siRNA Conjugates|Cyclodextrin-siRNA-β-CD环糊精修饰RNA核酸(解析说明)
猜你喜欢

Experience Sharing | Tips for Writing Easy-to-Use Online Product Manuals

私域增长 | 私域会员:9大连锁行业15个案例集锦

Thesis writing strategy | how to write an academic research paper

Private domain growth | Private domain members: 15 case collections from 9 major chain industries

Is it safe to use the MD5 encrypted string to store the password?Hash algorithm you have to know

4D Summary: 38 Knowledge Points of Distributed Systems

JMeter usage tutorial (2)

JSP Servlet JDBC MySQL CRUD 示例教程

荧光量子点修饰siRNA-QDs|纳米金修饰siRNA-Au(RNA修饰方式方法)

使用MD5加密后的字符串存密码安全吗?你不得不了解的Hash算法
随机推荐
2022中国物流产业大会暨企业家高峰论坛在杭州举办!
Baidu internship students late night fun: originally giant is this kind of life
Hyaluronic acid-siRNA透明质酸修饰核糖核酸|peptide–siRNA 多肽偶连RNA/DNA核酸(齐岳PNA修饰物)
C语言学习书籍 零基础入门篇
ESP8266-Arduino programming example-EEPROM read and write
PEG-siRNA-PCL|siRNA-PEG-LHRH|MPEG-siRNA 甲氧基聚乙二醇修饰核酸
[GXYCTF2019]禁止套娃
Detailed explanation of design ideas of webUI test framework
JSP Servlet JDBC MySQL CRUD 示例教程
朴素贝叶斯“朴素”在哪里?
RNA的化学修饰原理|Gal-PEG-siRNA|siRNA-S-S-DSPE|siRNA-s-s-PEG|cholesterol-siRNA
es6语法使用默认参数和解构
荣耀的野望:智慧世界的“高端平民”
Summary of scratch learning related materials
Related phrases include usage and collocation (include)
JMeter使用教程(一)
荧光量子点修饰siRNA-QDs|纳米金修饰siRNA-Au(RNA修饰方式方法)
RNA修饰技术介绍|介孔二氧化硅纳米颗粒(MSN)搭载的微小RNA-24(miR-24)纳米载体复合物
通过观测云监控器监控基础资源,自动报警
ESP8266-Arduino编程实例-I2C设备地址扫描