事件驱动的有限状态机中的转换
Transitions in an event-driven Finite State Machine
我在 python 中使用 Transitions 来实现有限状态机事件驱动。
我想实现一个 FSM,其中转换由通过避免 if/elif 语句处理的事件触发。
例如:我有一个 lamp 的简单 FSM,如果它(以非确定性方式)出现 'goInlampOn'
事件,我们将进入 'on' 状态,如果 'goInlampOff'
事件到达,我们将进入 'off'
状态。
所以我的问题是:
有没有办法在 FSM class 中创建一个名为 process_event(event)
的方法,该方法使用我的 FSM 的逻辑处理每个事件,而无需使用很长的(不是在这个非常简单的例子)if-elif语句?
代码示例如下:
class MyFsm(object):
transitions = [
{'trigger': 'switchOff', 'source':'on', 'dest':'off'},
{'trigger': 'switchOn', 'source':'off', 'dest':'on'}
]
def __init__(self):
''' initialating the FSM '''
self.machine = Machine(model=self, states=self.states,
transitions=self.transitions, initial='on')
on = On()
off = Off()
self.machine.add_state(off)
self.machine.add_state(on)
# A SMART SOLUTION TO IMPLEMENT THIS METHOD WITHOUT USING
# if state == off: ... elif state==on...
def process_event(self,event):
if self.state == 'off':
if event == 'goInlampOn':
self.switchOn()
elif self.state == 'on':
if event == 'goInlampOff':
self.switchOff()
在我介绍的情况下只有2个州,但如果我有10个或15个呢?
我尝试实施我认为@aleneum 向我建议的解决方案。然而,在这个解决方案中,我必须记录两次状态机的转换。
这是正确的 ?有没有更好的解决方案(避免两次编写转换)?
这是一个有 4 个状态(A、B、C、D)的状态机,唯一允许的转换是:
1. A->B
2. B->C
3. C->D
4. D->A
5. C->A
这里的代码:
from transitions import Machine
from states import A,B,C,D
class MyFsm(object):
transitions = [
{'trigger': 'go_in_B_fromA','source':'A','dest':'B'},
{'trigger': 'go_in_C_fromB','source':'B','dest':'C'},
{'trigger': 'go_in_D_fromC','source':'C','dest':'D'},
{'trigger': 'go_in_A_fromD','source':'D','dest':'A'},
{'trigger': 'go_in_A_fromC','source':'C','dest':'A'},
{'trigger': 'go_in_B_fromA','source':['C','D','B'],'dest':None},
{'trigger': 'go_in_C_fromB','source':['C','D','A'],'dest':None},
{'trigger': 'go_in_D_fromC','source':['B','D','A'],'dest':None},
{'trigger': 'go_in_A_fromD','source':['B','A','C'],'dest':None},
{'trigger': 'go_in_A_fromC','source':['D','A','B'],'dest':None}
]
def __init__(self):
self.machine = Machine(model=self, states = self.states ,transitions= self.transitions, initial = 'A' )
a = A()
b = B()
c = C()
d = D()
self.machine.add_state(a)
self.machine.add_state(b)
self.machine.add_state(c)
self.machine.add_state(d)
def process_event(self,event):
if event == 'go_in_B_fromA' :
self.go_in_B_fromA()
if event == 'go_in_C_fromB' :
self.go_in_C_fromB()
if event == 'go_in_D_fromC' :
self.go_in_D_fromC()
if event == 'go_in_A_fromD' :
self.go_in_A_fromD()
if event == 'go_in_A_fromC' :
self.go_in_A_fromC()
'''my main is something like this'''
myfsm = MyFsm()
while True:
event = event_from_external_bahaviour()
myfsm.process_event(event)
我不确定我是否理解您的问题,因为使用像转换这样的库的关键是避免编写长 if
-else if
链。此外,文档从未提及您应该重新实现 process_event()
.
所以我只能将文档解释为使用您的示例进行转换,而不能 ifs
。希望对你有帮助。
from transitions import Machine
class Model:
def __init__(self):
self.machine = Machine(
model=self,
states=["on", "off"],
transitions=[
{
"trigger": "switchOff",
"source": "on",
"dest": "off",
},
{
"trigger": "switchOn",
"source": "off",
"dest": "on",
},
],
initial="on",
ignore_invalid_triggers=True,
)
m = Model()
assert m.state == "on"
# We are in state 'on' and there is not 'switchOn'
# transition defined: nothing happens.
#
# Without `ignore_invalid_triggers`, transitions
# would raise an exception.
m.switchOn()
assert m.state == "on"
# We still are in 'on' and 'switchOff' brings
# us to 'off.
m.switchOff()
assert m.state == "off"
例如,您可以考虑阅读有关 UML 状态机的维基百科文章,因为转换非常接近实现它。
如@martineau 所述,events/the 模型行为的影响应由其当前状态决定。大块的 if/then 语句实际上是你想通过使用状态机来避免的。
看看下面的代码片段:
from transitions.core import Machine, State, MachineError
class On(State):
def __init__(self, *args, **kwargs):
super(On, self).__init__(*args, **kwargs)
class Off(State):
def __init__(self, *args, **kwargs):
super(Off, self).__init__(*args, **kwargs)
class MyFsm(object):
transitions = [
{'trigger': 'switchOff', 'source':'on', 'dest':'off'},
{'trigger': 'switchOn', 'source':'off', 'dest':'on'}
]
def __init__(self):
# ignore_invalid_triggers will allow to process events not defined for a state
on = On(name='on', ignore_invalid_triggers=True)
off = Off(name='off', ignore_invalid_triggers=False)
self.machine = Machine(model=self, states=[on, off], transitions=self.transitions, initial='on')
machine = MyFsm()
print(machine.state) # >>> on
machine.switchOff()
print(machine.state) # >>> off
try:
# this will raise a MachineException because there is no transition 'switchOff'
# defined in state 'off'
machine.switchOff() # raises MachineException
raise Exception("This exception will not be raised")
except MachineError:
pass
print(machine.state) # >>> off
machine.switchOn()
print(machine.state) # >>> on
# this will NOT raise an Exception since we configured 'on'
# to ignore transitions not defined for this state
machine.switchOn()
print(machine.state) # >>> on
我为 On
和 Off
定义了一些占位符 类,因为我假设您想使用自定义状态 类。 transitions
使您能够仅触发模型的方法而无需跟踪当前状态。您的配置将决定会发生什么。根据您的需要,如果触发了未为您的状态定义的方法,您可以提高 MachineError
。
考虑到您的示例,我建议忽略无效触发器,因为尝试打开或关闭 lamp 两次并不是什么大问题。
另一种解决方案是 'loop' 状态或使用 internal 转换,如果你想避免无效的触发器:
# leaves and enters state off even if its already off
# processes all on_enter/exit callbacks
{'trigger': 'switchOff', 'source':['on', 'off'], 'dest':'off'}
# an internal transition is defined by having dest set to 'None'
# processes no state callbacks
{'trigger': 'switchOff', 'source': 'off', 'dest': None}
这在很大程度上取决于您的用例和您使用此状态机实际控制的系统,首选哪种行为。
我在 python 中使用 Transitions 来实现有限状态机事件驱动。
我想实现一个 FSM,其中转换由通过避免 if/elif 语句处理的事件触发。
例如:我有一个 lamp 的简单 FSM,如果它(以非确定性方式)出现 'goInlampOn'
事件,我们将进入 'on' 状态,如果 'goInlampOff'
事件到达,我们将进入 'off'
状态。
所以我的问题是:
有没有办法在 FSM class 中创建一个名为 process_event(event)
的方法,该方法使用我的 FSM 的逻辑处理每个事件,而无需使用很长的(不是在这个非常简单的例子)if-elif语句?
代码示例如下:
class MyFsm(object):
transitions = [
{'trigger': 'switchOff', 'source':'on', 'dest':'off'},
{'trigger': 'switchOn', 'source':'off', 'dest':'on'}
]
def __init__(self):
''' initialating the FSM '''
self.machine = Machine(model=self, states=self.states,
transitions=self.transitions, initial='on')
on = On()
off = Off()
self.machine.add_state(off)
self.machine.add_state(on)
# A SMART SOLUTION TO IMPLEMENT THIS METHOD WITHOUT USING
# if state == off: ... elif state==on...
def process_event(self,event):
if self.state == 'off':
if event == 'goInlampOn':
self.switchOn()
elif self.state == 'on':
if event == 'goInlampOff':
self.switchOff()
在我介绍的情况下只有2个州,但如果我有10个或15个呢?
我尝试实施我认为@aleneum 向我建议的解决方案。然而,在这个解决方案中,我必须记录两次状态机的转换。
这是正确的 ?有没有更好的解决方案(避免两次编写转换)?
这是一个有 4 个状态(A、B、C、D)的状态机,唯一允许的转换是:
1. A->B
2. B->C
3. C->D
4. D->A
5. C->A
这里的代码:
from transitions import Machine
from states import A,B,C,D
class MyFsm(object):
transitions = [
{'trigger': 'go_in_B_fromA','source':'A','dest':'B'},
{'trigger': 'go_in_C_fromB','source':'B','dest':'C'},
{'trigger': 'go_in_D_fromC','source':'C','dest':'D'},
{'trigger': 'go_in_A_fromD','source':'D','dest':'A'},
{'trigger': 'go_in_A_fromC','source':'C','dest':'A'},
{'trigger': 'go_in_B_fromA','source':['C','D','B'],'dest':None},
{'trigger': 'go_in_C_fromB','source':['C','D','A'],'dest':None},
{'trigger': 'go_in_D_fromC','source':['B','D','A'],'dest':None},
{'trigger': 'go_in_A_fromD','source':['B','A','C'],'dest':None},
{'trigger': 'go_in_A_fromC','source':['D','A','B'],'dest':None}
]
def __init__(self):
self.machine = Machine(model=self, states = self.states ,transitions= self.transitions, initial = 'A' )
a = A()
b = B()
c = C()
d = D()
self.machine.add_state(a)
self.machine.add_state(b)
self.machine.add_state(c)
self.machine.add_state(d)
def process_event(self,event):
if event == 'go_in_B_fromA' :
self.go_in_B_fromA()
if event == 'go_in_C_fromB' :
self.go_in_C_fromB()
if event == 'go_in_D_fromC' :
self.go_in_D_fromC()
if event == 'go_in_A_fromD' :
self.go_in_A_fromD()
if event == 'go_in_A_fromC' :
self.go_in_A_fromC()
'''my main is something like this'''
myfsm = MyFsm()
while True:
event = event_from_external_bahaviour()
myfsm.process_event(event)
我不确定我是否理解您的问题,因为使用像转换这样的库的关键是避免编写长 if
-else if
链。此外,文档从未提及您应该重新实现 process_event()
.
所以我只能将文档解释为使用您的示例进行转换,而不能 ifs
。希望对你有帮助。
from transitions import Machine
class Model:
def __init__(self):
self.machine = Machine(
model=self,
states=["on", "off"],
transitions=[
{
"trigger": "switchOff",
"source": "on",
"dest": "off",
},
{
"trigger": "switchOn",
"source": "off",
"dest": "on",
},
],
initial="on",
ignore_invalid_triggers=True,
)
m = Model()
assert m.state == "on"
# We are in state 'on' and there is not 'switchOn'
# transition defined: nothing happens.
#
# Without `ignore_invalid_triggers`, transitions
# would raise an exception.
m.switchOn()
assert m.state == "on"
# We still are in 'on' and 'switchOff' brings
# us to 'off.
m.switchOff()
assert m.state == "off"
例如,您可以考虑阅读有关 UML 状态机的维基百科文章,因为转换非常接近实现它。
如@martineau 所述,events/the 模型行为的影响应由其当前状态决定。大块的 if/then 语句实际上是你想通过使用状态机来避免的。 看看下面的代码片段:
from transitions.core import Machine, State, MachineError
class On(State):
def __init__(self, *args, **kwargs):
super(On, self).__init__(*args, **kwargs)
class Off(State):
def __init__(self, *args, **kwargs):
super(Off, self).__init__(*args, **kwargs)
class MyFsm(object):
transitions = [
{'trigger': 'switchOff', 'source':'on', 'dest':'off'},
{'trigger': 'switchOn', 'source':'off', 'dest':'on'}
]
def __init__(self):
# ignore_invalid_triggers will allow to process events not defined for a state
on = On(name='on', ignore_invalid_triggers=True)
off = Off(name='off', ignore_invalid_triggers=False)
self.machine = Machine(model=self, states=[on, off], transitions=self.transitions, initial='on')
machine = MyFsm()
print(machine.state) # >>> on
machine.switchOff()
print(machine.state) # >>> off
try:
# this will raise a MachineException because there is no transition 'switchOff'
# defined in state 'off'
machine.switchOff() # raises MachineException
raise Exception("This exception will not be raised")
except MachineError:
pass
print(machine.state) # >>> off
machine.switchOn()
print(machine.state) # >>> on
# this will NOT raise an Exception since we configured 'on'
# to ignore transitions not defined for this state
machine.switchOn()
print(machine.state) # >>> on
我为 On
和 Off
定义了一些占位符 类,因为我假设您想使用自定义状态 类。 transitions
使您能够仅触发模型的方法而无需跟踪当前状态。您的配置将决定会发生什么。根据您的需要,如果触发了未为您的状态定义的方法,您可以提高 MachineError
。
考虑到您的示例,我建议忽略无效触发器,因为尝试打开或关闭 lamp 两次并不是什么大问题。
另一种解决方案是 'loop' 状态或使用 internal 转换,如果你想避免无效的触发器:
# leaves and enters state off even if its already off
# processes all on_enter/exit callbacks
{'trigger': 'switchOff', 'source':['on', 'off'], 'dest':'off'}
# an internal transition is defined by having dest set to 'None'
# processes no state callbacks
{'trigger': 'switchOff', 'source': 'off', 'dest': None}
这在很大程度上取决于您的用例和您使用此状态机实际控制的系统,首选哪种行为。